而不是使用pre_get_posts
过滤钩meta_query
在产品循环中,您可以使用专用的woocommerce_product_query_meta_query
过滤钩。
现在,对于您的问题,它可能是使用的小部件或短代码,因此还有一些专用的挂钩。
As the meta_query
对于 3 个挂钩函数来说是类似的,您可以在自定义函数中设置它并以这种方式在 3 个挂钩函数中调用它:
// The meta query in a function
function custom_meta_query( $meta_query ){
$meta_query[] = array(
'key'=>'city',
'value' => 'Cassis',
'compare'=>'NOT EXISTS',
);
return $meta_query;
}
// The main shop and archives meta query
add_filter( 'woocommerce_product_query_meta_query', 'custom_product_query_meta_query', 10, 2 );
function custom_product_query_meta_query( $meta_query, $query ) {
if( ! is_admin() )
return custom_meta_query( $meta_query );
}
// The shortcode products query
add_filter( 'woocommerce_shortcode_products_query', 'custom__shortcode_products_query', 10, 3 );
function custom__shortcode_products_query( $query_args, $atts, $loop_name ) {
if( ! is_admin() )
$query_args['meta_query'] = custom_meta_query( $query_args['meta_query'] );
return $query_args;
}
// The widget products query
add_filter( 'woocommerce_products_widget_query_args', 'custom_products_widget_query_arg', 10, 1 );
function custom_products_widget_query_arg( $query_args ) {
if( ! is_admin() )
$query_args['meta_query'] = custom_meta_query( $query_args['meta_query'] );
return $query_args;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。
这应该有效...