在 WooCommerce 中获取和显示产品的销售数量

Get and display products On Sale count in WooCommerce

通过执行 SQL 查询(似乎无法正常工作)计算有多少产品在打折(计算有多少产品有折扣价),我的目标是显示一条消息使用挂钩在主存档(商店)上。该消息应包含计数(有多少产品在打折)。

期望的示例输出:"Looking for a great deal? We currently have XX products on sale!"

关于为什么这不起作用的任何想法或见解? 这是我的代码:

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>';

库存状态与 "on sale" 产品无关,_on_sale 元值不存在,因此您的 SQL 查询不起作用。

促销产品已定义 "sale price",因此尝试改用:

function get_onsale_products_count() {
    global $wpdb;

    // SQL query for counting products that are on sale
    return $wpdb->get_var( "
        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 = 'publish'
        AND pm.meta_key = '_sale_price'
        AND pm.meta_value != ''
    " );
}

add_action( 'woocommerce_before_single_product_summary', 'display_onsale_products_count_message', 3 );
function display_onsale_products_count_message(){
    echo '<span class="great-deal">' . sprintf( __( "Want to make a good deal? We've got %s products on sale!" ), 
    get_onsale_products_count() ) . '</span>';
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。