繁体   English   中英

在WP_Query中限制Woocommerce特色产品

[英]Limit Woocommerce featured products in a WP_Query

我想在网站标题中获得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中。 使用woocommerce3.x。

您应该使用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;
}

首先,由于Woocommerce 3,您的代码有些过时了,因为get_product 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文件中的这段代码,它应该对您有用...

与Woocommerce 3之前的版本一样,“功能产品”由发布元数据(元查询)处理,您可能需要更新产品条款计数,方法是转到Woocommerce设置>状态>工具。 “期限计数”部分中,单击“重新计量期限”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM