Avoid add to cart for specific product categories if user is unlogged in Woocommerce

后端 未结 2 396
孤独总比滥情好
孤独总比滥情好 2020-12-21 18:35

In Woocommerce, I am trying to disable specific product categories to be added to the cart for users that aren\'t logged in. i\'m looking for a solution the last couple of d

2条回答
  •  旧时难觅i
    2020-12-21 19:23

    woocommerce_is_purchasable filter can do the job. It checks if a product is purchasable or not. If not purchasable, "add-to-cart" button is removed and can't be purchased.

    So, here you will need to check if user is logged in or not, and product belongs to certain category, before disabling purchase ability.

    This is how you can do it:

    function wpso9800_remove_cart_button( $is_purchasable, $product ) {
        //when logged in
        if ( is_user_logged_in() ) {
            return $is_purchasable;
        }
    
        //get categories
        $categories = get_the_terms( $product->id, 'product_cat');
        $my_terms_ids = array ( 1, 2 );//product category IDs
    
        if ($categories && !is_wp_error($categories)) {
            foreach ($categories as $cat) {
                if ( in_array($cat->term_id, $my_terms_ids ) ) {
                    return false;
                }
                return $is_purchasable;
            }
        }
    }
    add_filter('woocommerce_is_purchasable','wpso9800_remove_cart_button', 10, 2);
    

    **This is tested, and working.

    Note: By default, $is_purchasable is set to true. You will need to return false, when you want to turn off purchasing.

提交回复
热议问题