首页 > 解决方案 > 在 WP_Query 中限制 Woocommerce 特色产品

问题描述

我想在网站的标题中获得 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。

标签: phpwordpresswoocommerceproductcustom-taxonomy

解决方案


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

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

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

我不想建议它,但如果你不知道为什么它返回 20 个帖子而不是 2 个,你可以只breakwhile一个计数器循环:

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

推荐阅读