Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexdeborba/14389d06fd060a8d53f0af861a8e4cdf to your computer and use it in GitHub Desktop.
Save alexdeborba/14389d06fd060a8d53f0af861a8e4cdf to your computer and use it in GitHub Desktop.
WooCommerce: Action to limit User Role to a number items per Order
// Add an action on cart evaluation
add_action( 'woocommerce_check_cart_items', 'limit_cart_items_for_specific_role' );
function limit_cart_items_for_specific_role() {
// The user role to check against
$user_role_to_check = 'subscriber';
// The item limit
$item_limit = 3;
// Get the current user
$current_user = wp_get_current_user();
// If the current user has the role to check and the number of items in the cart exceeds the limit
if ( in_array( $user_role_to_check, $current_user->roles ) && WC()->cart->get_cart_contents_count() > $item_limit ) {
// Display an error message and prevent checkout
wc_add_notice( sprintf( __( 'As a %s, you are limited to %s items per order.', 'woocommerce' ), $user_role_to_check, $item_limit ), 'error' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment