获取WooCommerce当月最畅销的产品

时间:2019-04-30 作者:crslz

我正在努力获得WooCommerce本月最畅销的产品。

以下代码可以很好地获得最畅销的产品:

$query_args = array(
    \'posts_per_page\' => $number,
    \'post_status\'    => \'publish\',
    \'post_type\'      => \'product\',
    \'no_found_rows\'  => 1,
    \'meta_key\'       => \'total_sales\',
    \'orderby\'        => \'meta_value_num\',
    \'order\'          => \'desc\',
    \'meta_query\'     => array(),
    \'tax_query\'      => array(
        \'relation\' => \'AND\',
    ),
); // WPCS: slow query ok.
现在,我正在努力获得本月最畅销的产品,但它无法正常工作:

$query_args = array(
    \'posts_per_page\' => $number,
    \'post_status\'    => \'publish\',
    \'post_type\'      => \'product\',
    \'no_found_rows\'  => 1,
    \'meta_key\'       => \'total_sales\',
    \'orderby\'        => \'meta_value_num\',
    \'order\'          => \'desc\',
    \'date_query\' => array(
        array(
            \'year\' => date( \'Y\' ),
            \'month\' => date( \'m\' ),
        ),
    ),
    \'meta_query\'     => array(),
    \'tax_query\'      => array(
        \'relation\' => \'AND\',
    ),
); // WPCS: slow query ok.

1 个回复
SO网友:LoicTheAztec

不可能在畅销产品上使用日期total_sales 不能与任何日期相关。

为了实现这一点,应该需要使用WPDB 类和类似于此自定义函数的SQL查询(使用可选参数限制产品数量):

function get_best_selling_products( $limit = \'-1\' ){
    global $wpdb;

    $limit_clause = intval($limit) <= 0 ? \'\' : \'LIMIT \'. intval($limit);
    $curent_month = date(\'Y-m-01 00:00:00\');

    return (array) $wpdb->get_results("
        SELECT p.ID as id, COUNT(oim2.meta_value) as count
        FROM {$wpdb->prefix}posts p
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim
            ON p.ID = oim.meta_value
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim2
            ON oim.order_item_id = oim2.order_item_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_items oi
            ON oim.order_item_id = oi.order_item_id
        INNER JOIN {$wpdb->prefix}posts as o
            ON o.ID = oi.order_id
        WHERE p.post_type = \'product\'
        AND p.post_status = \'publish\'
        AND o.post_status IN (\'wc-processing\',\'wc-completed\')
        AND o.post_date >= \'$curent_month\'
        AND oim.meta_key = \'_product_id\'
        AND oim2.meta_key = \'_qty\'
        GROUP BY p.ID
        ORDER BY COUNT(oim2.meta_value) + 0 DESC
        $limit_clause
    ");
}
它将输出一个按产品计数描述排序的对象数组,每个对象包含产品ID和计数。

用法示例(仅限本月5款畅销产品):

$best_selling_products = get_best_selling_products( 5 );

// Loop through best selling products stdClass Objects
foreach( $best_selling_products as $values ) {
    $product_id    = $values->id; // Get the product ID
    $product_count = $values->count; // Get the count for the current month
}

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post