I am searching for a conditional shortcode based on product price. I have 2k+ products on Woocommerce now and I want to show products above 99$ price from a specific category an
Update on August 2018: (added 'type' => 'DECIMAL', to the meta_query array)
For WooCommerce 3.3+ you can better use:
Display on a page all products below a specific price in Woocommerce
This is possible tweaking the shortcode with a fake category that contain the price like for your case: price-above-99
where 'above'
will be the operator '>'
and '99'
the price amount. The operator can also be:
price-below-20
( where 'below'
the operator '<'
and '20'
the price amount ).price-equal-25
( where 'below'
the operator '='
and '25'
the price amount ).Now your shortcode (with the fake category) will be:
[products limit="10" columns="4" category="hoodies, tshirts, price-above-99"]
Here is the code of the function that will allow that:
add_filter( 'woocommerce_shortcode_products_query', 'shortcode_products_price', 10, 3 );
function shortcode_products_price( $query_args, $atts, $loop_name ) {
$has_price = false;
$compare = $price = '';
$categories = $atts['category'];
$categories = str_replace(' ', '', $categories);
$categories_array = explode(',', $categories);
if( count($categories_array) > 0 )
foreach( $categories_array as $category )
if (strpos($category, 'price-') !== false) {
$has_price = true;
$values = explode('-', $category);
if( 'above' == $values[1] ) $compare = '>';
elseif( 'below' == $values[1] ) $compare = '<';
else $compare = '=';
$price = $values[2];
}
if( $has_price )
$query_args['meta_query'][] = array(
'key' => '_price',
'value' => $price,
'type' => 'DECIMAL', // <== Updated
'compare' => $compare,
);
return $query_args;
}
Code goes in function.php file of the active child theme (or active theme).
It works quiet well on simple products, but for variable products, as they have many prices, it will take the highest price (in your case)...
If you want to exclude variable products you will replace the meta query array $query_args['meta_query']
by this:
if( $has_price )
$query_args['meta_query'][] = array(
'relation' => 'OR',
array(
'key' => '_regular_price',
'value' => $price,
'type' => 'DECIMAL', // <== Updated
'compare' => $compare,
),
array(
'key' => '_sale_price',
'value' => $price,
'type' => 'DECIMAL', // <== Updated
'compare' => $compare,
)
);
This will remove variable products …