如何使用wp_query woocommerce获得最畅销的产品

时间:2018-09-07 07:39:43

标签: php wordpress woocommerce product

我想在首页上获得“最畅销产品”。我正在使用以下查询,但这并不是所有类别中最畅销的产品。

如果我将最畅销的产品短代码放在一边,但自定义结构无法获得这些产品。 这些“我的查询功能”。

function get_product_posts_hp()
{
    wp_reset_query();
    $args = array(
        'posts_per_page' => 12,
        'post_type' => 'product',
        'post_status' => 'publish',
        'ignore_sticky_posts'   => 1,
        'meta_key' => 'total_sales',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
    );
    return new WP_Query($args);
}

Thanks In Advance..

1 个答案:

答案 0 :(得分:1)

您的代码在全球范围内均可使用...我尝试使用以下功能代码:

function get_product_posts_hp(){
    $query = new WP_Query( array(
        'posts_per_page' => 12,
        'post_type' => 'product',
        'post_status' => 'publish',
        'ignore_sticky_posts' => 1,
        'meta_key' => 'total_sales',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
    ) );

    echo '<p>Count: '. $query->post_count ; '</p>';

    if($query->have_posts()) :
        while($query->have_posts()) : $query->the_post();

            echo '<p>' . get_the_title() . ' (';
            echo get_post_meta( get_the_id(), 'total_sales', true) . ')</p>';

        endwhile;
        wp_reset_postdata();
    endif;
}

我得到了按销售总额DESC显示的12个产品标题。