hide products from users who are not logged in (us

2019-05-23 22:53发布

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.

What I Have Currently

$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;
        }
    }
}

See Gist: https://gist.github.com/DerekFoulk/d94646da9f22d5dddff6

The results of my efforts can be seen on this page: http://gigacord.com/shop/

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.

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).

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?

1条回答
萌系小妹纸
2楼-- · 2019-05-23 23:14

it's better you use pre_get_posts

here...

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' );
查看更多
登录 后发表回答