I'm woocommerce 2.8, How can I count the products existing in the shop "on sale" for a specific category (ex: computers) ?
I found a way to count all products :
$count_posts = wp_count_posts( 'product' );
return $count_posts->publish;
But how can I get the number of products "on-sale" for a specific category ?
Thanks
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => here goes your category id, you can also go for slug
)
),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array(
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
$query = new WP_Query($args);
$onSaleCount = $query->found_posts;
The above looks for simple and variable products on sale belonging to a category mentioned under tax_query
.
I'm not sure if there's a better method, but this should work.
LE - Changed args to exclude products out of stock as per comments.
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => here goes your category id, you can also go for slug
)
),
'meta_query' => array(
'relation' => 'AND',
array(
'relation' => 'OR',
array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array(
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
),
array(
'key' => '_stock_status',
'value' => 'instock'
),
)
);