Search code examples
phpwoocommerceproducthook-woocommerceproduct-quantity

Change quantity steps depending on the user role of the in WooCommerce


In WooCommerce, I am trying to change the product quantity field settings as step depending on user role and product.

Here is my code

add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products
function jk_woocommerce_quantity_input_args( $args, $product, $roles ) {
    if ( is_singular( 'product' ) ) {
        if( $product->get_id() == 85 ) {
            $args['input_value'] = 30;
        } else {
            $args['input_value'] = 5;
        }
    }

    if( array ( $roles, 'customer_roles')) {
        $args['min_value']      = 1;
         $args['step']           = 1;               
    }

    if( $product->get_id() == 85 ) {
            $args['min_value'] = 30;
            $args['step']      = 5;
        } else {
            $args['min_value'] = 5;
            $args['step']      = 5;
        }
        return $args;
}

How can I make this code working for user roles too?


Solution

  • There are some mistakes in your code, like $roles variable doesn't exist for this hook argument and some others… Try the following:

    add_filter( 'woocommerce_quantity_input_args', 'quantity_input_args_filter_callback', 10, 2 );
    function quantity_input_args_filter_callback( $args, $product ) {
        // HERE define the user role:
        $user_role = 'customer_roles';
    
        $user = wp_get_current_user(); // Get the WP_Use Object
    
        // For a specific user role, we keep default woocommerce quantity settings
        if( in_array( $user_role, $user->roles ) ) 
            return $args; // Exit to default
    
        // For the others as following
    
        if ( is_singular( 'product' ) ) {
            if( $product->get_id() == 85 ) {
                $args['input_value'] = 30;
            } else {
                $args['input_value'] = 5;
            }
        }
    
        if( $product->get_id() == 85 ) {
            $args['min_value'] = 30;
            $args['step']      = 5;
        } else {
            $args['min_value'] = 5;
            $args['step']      = 5;
        }
        return $args;
    }
    

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