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

B.V*_*mar 6 php wordpress product woocommerce

我想在主页上获得最畅销的产品。我正在使用下面的查询但这并没有获得所有类别的最畅销产品。

如果我放置最畅销的产品短代码,该代码有效,但自定义结构无法获得这些产品。这些我的查询功能..

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..
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 8

您的代码在全局范围内工作\xe2\x80\xa6 我已尝试使用以下功能代码:

\n\n
function get_product_posts_hp(){\n    $query = new WP_Query( array(\n        'posts_per_page' => 12,\n        'post_type' => 'product',\n        'post_status' => 'publish',\n        'ignore_sticky_posts' => 1,\n        'meta_key' => 'total_sales',\n        'orderby' => 'meta_value_num',\n        'order' => 'DESC',\n    ) );\n\n    echo '<p>Count: '. $query->post_count ; '</p>';\n\n    if($query->have_posts()) :\n        while($query->have_posts()) : $query->the_post();\n\n            echo '<p>' . get_the_title() . ' (';\n            echo get_post_meta( get_the_id(), 'total_sales', true) . ')</p>';\n\n        endwhile;\n        wp_reset_postdata();\n    endif;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n