Skip to content
WooCommerce + Groups

Request

  • Restrict a list of SKUs from being purchased by a specific group

The site uses the Force Sells Extension from WooThemes, but the plugin isn’t required to use the below code. The SKUs listed in the original from below were part of a larger grouped product and individual non-display wasn’t possible through the UI.

Required Plugins

Code

<?php
$group_num  =  <GROUP_ID>;
$disallowed_product_skus  =  array (
    $group_num    =>  array (
        '<SKU>',
        )
);
 
add_filter ( 'woocommerce_before_cart' , 'cart_check_disallowed_skus' );
function cart_check_disallowed_skus() {
 
  if ( is_cart( ) ) {
    global $woocommerce;
    global $disallowed_product_skus;
 
    $user_id = get_current_user_id();
    $user = new Groups_User( $user_id );
    $groups = $user->groups;
    $assigned_group = $groups[0]->group->group_id;
 
    $cart_contents = $woocommerce->cart->get_cart();
    $cart_keys = array_keys ( $cart_contents );
 
    if ( array_key_exists ( $assigned_group , $disallowed_product_skus ) ) {
        $disallowed_products_in_cart  =  false;
        foreach ( $cart_keys as $key ) {
            $cart_item_product_id = $cart_contents[$key]['product_id'];
            $cart_product_meta = get_post_meta ( $cart_item_product_id );
            $cart_product_sku = $cart_product_meta['_sku'][0];
 
            if ( in_array ( $cart_product_sku , $disallowed_product_skus[$assigned_group] ) ) {
                // Set quantity to zero if the product is in the disallowed list
                $woocommerce->cart->set_quantity ( $key , 0 , true );
                $disallowed_products_in_cart = true;
            }
        }
 
        if ( $disallowed_products_in_cart ) {
            echo '<p class="woocommerce-error">Non-approved products have been automatically removed from cart.</p>';  
        }
    }
  }
}
?>

Display

Cart

Image: Display of error message displayed to customer when disallowed products have been removed from their cart

Disclaimer

Purrly Digital LLC cannot be held responsible for the functionality of this code. Please make sure you test it on a development site before adding the code to your production website. There is no support available for this (and other) code snippet(s) posted on this website. If you’d like Purrly Digital to do custom development to help with your custom implementation please send a contact request.

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top