Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WooCommerce custom quantity input step for each cart item based on custom field

I am using woocommerce_quantity_input_args hook in PHP snippet, I’ve got a number saved in metadata for each product and I want to apply that metadata to $args['step'] for each quantity step in cart as they aren’t all the same.

Code:

add_filter( 'woocommerce_quantity_input_args', 'woocommerceQuantityInputArgs', 10, 2);
function woocommerceQuantityInputArgs( $args, $product ) {
    if ( ! is_cart() ) {
        $cart = WC()->cart->get_cart();
        foreach( $cart as $cart_item_key => $cart_item ){
            $product = $cart_item['data'];
            $args['step'] = $product->get_meta('_quantity_product_in_package');
        }
    }
}

I’ve tried saving all the meta data in a seperate array and loop through it and apply it to $args, but it didn’t work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are some mistakes in your current code, try the following instead:

add_filter( 'woocommerce_quantity_input_args', 'cart_item_quantity_input_step', 100, 2);
function cart_item_quantity_input_step( $input_args, $product ) {
    $input_args['step'] = $product->get_meta('_quantity_product_in_package');

    return $input_args;
}

To limit that only on cart page, use:

add_filter( 'woocommerce_quantity_input_args', 'cart_item_quantity_input_step', 100, 2);
function cart_item_quantity_input_step( $input_args, $product ) {
    if ( is_cart() ) {
        $input_args['step'] = $product->get_meta('_quantity_product_in_package');
    }
    return $input_args;
}

Code goes in functions.php file of your child theme (or in a plugin). It should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading