Created
June 8, 2023 12:53
-
-
Save alexdeborba/14389d06fd060a8d53f0af861a8e4cdf to your computer and use it in GitHub Desktop.
WooCommerce: Action to limit User Role to a number items per Order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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