对未登录的用户隐藏产品(使用标签)? [英] hide products from users who are not logged in (using tags)?
问题描述
非常简单的概念......如果用户未登录,我想在 WooCommerce 的任何地方隐藏所有带有批发"标签的产品......我已经接近了,但还没有骰子.
Pretty simple concept... I want to hide all products that have the tag "Wholesale" from everywhere in WooCommerce if the user is not logged in... I have gotten close, but no dice just yet.
我目前拥有什么
$product_tags = wp_get_post_terms( $product->id, 'product_tag' );
if ( ! empty( $product_tags ) ) {
foreach( $product_tags as $tag ) {
if ( $tag->slug === 'wholesale' && ! is_user_logged_in() ) {
return;
}
}
}
参见要点:https://gist.github.com/DerekFoulk/d94646da9f22d5dddff6
我的努力成果可以在这个页面看到:http://gigacord.com/shop/
The results of my efforts can be seen on this page: http://gigacord.com/shop/
从结果中可以看出,产品网格中存在漏洞,因为该行应该在产品 1/3(每行)和 上具有类
项目 3/3.我目前正在删除"产品的地方显然是在计算每行项目然后分配所述类的逻辑之后..first
.last
As you can see from the results, there are holes in the product grid because the row is supposed to have the class .first
on product 1/3 (on each row) and .last
on item 3/3. Where I am currently "removing" the product is apparently after the logic that counts the items per row and then assigns said classes.
这个片段并没有做我想做的一切.简而言之,我想尽快从 products 数组中删除产品(在我的主题可以开始构建其元素之前).我还想在直接访问产品页面时隐藏所有产品信息(虽然可能是一个不同的问题).
This snippet does not do everything I would like. In a nutshell, I would like to remove the product from the products array as soon as possible (before my theme can start constructing its elements). I would also like to hide all product information when the product page is accessed directly (probably a different question though).
那么,是否有一个 WooCommerce 挂钩可以在显示产品的任何地方运行?如果有,我该如何使用该挂钩隐藏带有批发"标签的产品?
So, is there a WooCommerce hook that runs everywhere products are displayed, and if so, how can I hide the products that have the tag of "Wholesale" using that hook?
推荐答案
最好使用 pre_get_posts
这里...
function rei_exclude_by_product_tag( $query ) {
if ( $query->is_main_query() && is_woocommerce() && !is_user_logged_in() ) {
$taxquery = array(
array(
'taxonomy' => 'product_tag',
'field' => 'id',
'terms' => array( 6 ), // the ID of the product tag
'operator'=> 'NOT IN' // exclude
)
);
$query->set('tax_query', $taxquery);
}
}
add_action( 'pre_get_posts', 'rei_exclude_by_product_tag' );
这篇关于对未登录的用户隐藏产品(使用标签)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!