php - 自定义 WooCommerce 产品查询不起作用
问题描述
我正在尝试创建此自定义产品查询,以仅在/shop
页面上显示具有以下内容的产品tax_query
。但它不起作用。
我也试过woocommerce_product_query
钩子。
感谢任何建议!
add_action( 'pre_get_posts', 'show_active_lotteries_only' );
function show_active_lotteries_only( $q ){
$q->set( 'tax_query', array (
array(
'fields' => 'ids',
'post_type'=> 'product',
'show_past_lottery' => FALSE,
'tax_query' => array(array('taxonomy' => 'product_type' , 'field' => 'slug', 'terms' => 'lottery')),
)
));
}
The query is taken from the lottery plugin documentation (the product being used in the store):
// Return active lottery products.
$args = array(
'fields' => 'ids',
'post_type'=> 'product',
'show_past_lottery' => FALSE,
'tax_query' => array(array('taxonomy' => 'product_type' , 'field' => 'slug', 'terms' => 'lottery')),
);
解决方案
因此,对于您的条件检查,您是否shop page
可以使用以下 woocommerce 功能:
// This will make sure that you're on the shop page
is_shop();
此外,为了编写您的tax_query
内容,您可以将所有数组/过滤器分配给一个变量,如下所示:
$tax_query = array(
// If you have multiple filters/arrays then
// You could also assign a relationship to these filters
// 'relation' => 'AND'/'OR'
array(
'taxonomy' => 'product_type',
'field' => 'slug',
'terms' => 'lottery'
),
// Another array/filter
// array(
// ...YOUR ARGs HERE...
// )
);
所以最终的代码会是这样的:
add_action('pre_get_posts', 'show_active_lotteries_only');
function show_active_lotteries_only($q)
{
if (is_shop()) {
$tax_query = array(
array(
'taxonomy' => 'product_type',
'field' => 'slug',
'terms' => 'lottery'
)
);
$q->set('tax_query', $tax_query);
$q->set('post_type', 'product');
$q->set('post_status', 'publish');
$q->set('fields', 'ids');
$q->set('show_past_lottery', FALSE);
}
}
推荐阅读
- c - irq.h or irqflags.h disable interrupts Raspberry
- javascript - Node JS log all function execution in order of execution
- java - Java:在不同的库中使用相同的包名是不好的做法吗?
- java - 通过数组创建索引循环并打印元素?
- python - How to slice a pandas DataFrame based on a subset of the levels in a MultiIndex
- php - Prestashop - migrate module 1.7 -> 1.6 (field name is empty)
- arrays - Julia 编写 k 步前瞻函数的方法?
- maven - 使用命令行创建 MAVEN 项目时出错
- python - 如何在 python folium 的图层之间使用 MarkerCluster?
- java - 无论我是否正确输入,Java 都没有运行我的扫描仪