gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:21:05 24 4
gpt4 key购买 nike

我想从我的商店页面中排除来自给定城市的产品,但也想从我的主页中排除产品,在主页上我显示来自平面 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_querypre_get_posts 过滤 Hook 用于 meta_query on products 循环 过滤器钩子(Hook)。

现在对于您的问题,它可能是使用的小部件或简码,因此还有一些专门用于它们的 Hook 。

由于 meta_query 对于 3 个 Hook 函数来说是相似的,您可以在自定义函数中设置它并以这种方式在 3 个 Hook 函数中调用它:

// 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 文件。

这应该可以……

关于php - 使用 Woocommerce 中的元查询从任何地方排除特定产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com