在Woocommerce中使用元查询从任何地方排除特定产品



我想从我的商店页面中排除来自给定城市的产品,但也想从我的主页中排除产品,在那里我展示了来自扁平的UX Builder的woocommerce商店小部件的产品(不确定它是一个小部件)。

具有给定城市的产品不会出现在我的商店页面中,但它们仍然出现在我的主页中。

add_filter( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ($q->is_main_query())
{
$meta_query = $q->get('meta_query');
$meta_query[] = array(
'key'=>'city',
'value' => 'Cassis',
'compare'=>'NOT EXISTS',
);
$q->set('meta_query',$meta_query);
remove_filter( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
}

知道吗?

您可以使用专用的woocommerce_product_query_meta_query筛选器钩子,而不是使用pre_get_posts筛选器钩子进行产品循环meta_query

现在对于您的问题,它可能是使用的小部件或短代码,因此也有一些专用的钩子。

由于 3 个挂钩函数的meta_query相似,因此您可以在自定义函数中设置它,并以这种方式在 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;
}

代码进入函数.php活动子主题(或活动主题)的文件。

这应该有效...

最新更新