限制Woocommerce在WP_Query中展示产品

问题描述 投票:1回答:2

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

php wordpress woocommerce product custom-taxonomy
2个回答
2
投票

首先你的代码有点过时了,因为作为get_product()的Woocommerce 3需要被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文件上成功测试了这段代码...

与之前的Woocommerce 3一样,“特色产品”由后期元数据(元查询)处理,您可能需要更新产品术语计数到Woocommerce设置>状态>工具。在“期限计数”部分中,点击“重新计算条款”。


2
投票

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

如果这不能解决您的问题,请确保任何其他自定义循环使用适当的重置,和/或尝试重命名变量$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;
}
© www.soinside.com 2019 - 2024. All rights reserved.