php - 在 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。
解决方案
您应该使用wp_reset_postdata()
而不是wp_reset_query()
因为WP_query
不会覆盖主查询。
如果这不能解决您的问题,请确保任何其他自定义循环使用适当的重置,和/或$featured_query
如果您在其他地方使用它,请尝试重命名该变量 - 它可能是从前一个循环继承帖子。
您也可以尝试添加'nopaging' => true
and'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;
}
推荐阅读
- javascript - 无法在 Electron 应用程序中修改应用程序菜单
- kotlin - Kotlin:以相反的顺序遍历数组
- java - while 语句中的无限循环
- c++ - 如何在 C++14 中保留左值引用的同时衰减右值引用类型?
- c - 如何使用正确的 while 循环使文件显示?
- java - 使用 Spring Cloud Circuit Breaker 时避免在 NoFallbackAvailableException 中包装原因
- sql-server - 为 SQL Server 中的数字列选择最佳数据类型
- python - 如何减少在 python 中加载泡菜文件或将泡菜文件映射到磁盘的时间
- html - 如何使用每种颜色类别 HTML/CSS 的空白创建彩色线条?
- matlab - 如何使条形图从空白变为彩色?