By doing an SQL query (does not seem to work properly) which counts how many products that are on sale (it counts how many products that have discounted prices), my goal is to display a message on the main archive (shop) using a hook. The message should contain the count (how many products that are on sale).
Desired example output: "Looking for a great deal? We currently have XX products on sale!"
Any ideas or insight as to why this is not working? Here's my code:
function get_onsale_products_count() {
global $wpdb;
// SQL query for counting products that are on sale
$result = $wpdb->get_col( "
SELECT COUNT(p.ID)
FROM {$wpdb->prefix}posts as p
INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type LIKE '%product%'
AND p.post_status LIKE 'publish'
AND pm.meta_key LIKE '_stock_status'
AND pm.meta_value LIKE '_on_sale'
" );
return reset($result);
}
add_action('woocommerce_before_single_product_summary', 'get_onsale_products_count');
$count = get_onsale_products_count();
$great_deal = sprintf( __( 'Want to make a good deal? We\'ve got %s products on sale!' ), $count );
echo '<span class="great-deal">'.$great_deal.'</span>';