将 Woocommerce 特色产品限制在 WP_Query

Limit Woocommerce featured products in a WP_Query

我想在网站的 header 中获得 3 个特色产品。但是我的查询一直返回无限数量的结果。

我一直在网上寻找解决方案,发现所有答案都在查询方面说了同样的话。我可能做错了什么?

$meta_query  = WC()->query->get_meta_query();
$tax_query   = WC()->query->get_tax_query();
$tax_query[] = array(
    'taxonomy' => 'product_visibility',
    'field'    => 'name',
    'terms'    => 'featured',
    'operator' => 'IN',
);

$args = array(
    'post_type'           => 'product',
    'post_status'         => 'publish',
    'posts_per_page'      => 2,
    'meta_query'          => $meta_query,
    'tax_query'           => $tax_query,
);

$featured_query = new WP_Query( $args );

if ($featured_query->have_posts()) {

    while ($featured_query->have_posts()) : 

        $featured_query->the_post();

        $product = get_product( $featured_query->post->ID );

        echo $product->title; echo "test";
        // Product info here

    endwhile;

}

wp_reset_query();

以下查询返回了 20 个结果。代码放在 header.php 中。使用 woocommerce 3.x.

您应该使用 wp_reset_postdata() instead of wp_reset_query(),因为 WP_query 不会覆盖主查询。

如果这不能解决您的问题,请确保任何其他自定义循环使用适当的重置,and/or 尝试重命名变量 $featured_query 如果您在别处使用它 - 它可能是从上一个循环继承帖子。

您也可以尝试添加 'nopaging' => true'ignore_sticky_posts' => true 参数

我不想推荐它,但如果你不明白为什么它返回 20 个帖子而不是 2 个,你可以 break 你的 while 循环和一个计数器:

if ($featured_query->have_posts()) {
    $counter = 0;
    while ($featured_query->have_posts()) : $featured_query->the_post();

        /* Do post stuff here */

        $counter++;

        if( $counter == 2 ) break;
    endwhile;
}

首先,您的代码有点过时,因为 Woocommerce 3,因为 get_product() 需要替换为 wc_get_product()$product->title; 需要替换为 $product->get_title();...
完成后,您的代码可以运行,您将获得 3 个特色产品:

$meta_query  = WC()->query->get_meta_query();
$tax_query   = WC()->query->get_tax_query();
$tax_query[] = array(
    'taxonomy' => 'product_visibility',
    'field'    => 'name',
    'terms'    => 'featured',
    'operator' => 'IN',
);

$featured = new WP_Query( array(
    'post_type'           => 'product',
    'post_status'         => 'publish',
    'posts_per_page'      => 3, // <==  <==  <==  3 products
    'meta_query'          => $meta_query,
    'tax_query'           => $tax_query,
) );

// Get the products count in the query
echo '<p>Featured products count: ' .$featured->post_count . '</p>';

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

    $product = wc_get_product( $featured->post->ID );

    echo $product->get_title() . '<br>';
    // Product info here

endwhile; endif;

wp_reset_postdata();

它应该对你有用,因为我已经在 header.php 文件上成功测试了这段代码…

As before Woocommerce 3, the "featured products" where handled by post meta data (a meta query), you may need to update product terms count going to Woocommerce settings > status > tools. In "Term counts" section click on "Recount terms".