Search code examples
phpwordpresswoocommercecartuser-roles

Restrict to only one item in cart for specific user roles in Woocommerce


I've made a Woocommerce giftshop for a client. Their customers are other business that let their employees select their gift through the webshop. Each business have 1 login that all employees use. As of right now, every user is only allowed 1 item in their cart. If another product is selected, it will overwrite the previous.

Today I was informed that they wish to expand so it will be possible for select users/user roles to have more than 1 product in their cart and "purchase" them. Money transactions are not handled directly on the webshop, so purchasing the products sends a list to my client and they take it from there

The current code I use to impose this limit is the following:

add_filter( 'woocommerce_add_to_cart_validation', 'custom_only_one_in_cart', 99, 2 );
function custom_only_one_in_cart( $passed, $added_product_id ) {

    // empty cart first: new item will replace previous
    wc_empty_cart();

    // display a message if you like
    wc_add_notice( 'Max number of items in cart reached!', 'notice' );

    return $passed;
}

So I'm looking for ideas on how to implement this on specific users or user roles, so the end result will be that most users can only pick one, while a few select user can pick more.

I've already been looking around a lot for a suitable solution, but I haven't been able to find one as of yet.

The solution doesn't have to incorporate the code I provided, either in its current state or in a variation of it, all suitable solutions are welcome.

Any help is appreciated.


Solution

  • In the following code will restrict add to cart to only one item based on defined allowed user roles:

    add_filter( 'woocommerce_add_to_cart_validation', 'user_roles_only_one_in_cart', 50, 3 );
    function user_roles_only_one_in_cart( $passed, $product_id, $quantity ) {
        // HERE define the User roles that are allowed to buy multiple items:
        $allowed_user_roles = array('special_customer','administrator', 'shop_manager');
    
        $user = wp_get_current_user();
    
        if( array_intersect( $allowed_user_roles, $user->roles ) )
            return $passed;
    
        // Check if cart is empty
        if( ! WC()->cart->is_empty() ){
            // display an error notice
            wc_add_notice( __("Only one item in cart is allowed!", "woocommerce"), "error" );
            // Avoid add to cart
            $passed = false;
        }
    
        return $passed;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    enter image description here

    For user roles creation and management you can use User Role Editor plugin (for example).