Search code examples
phpwordpresswoocommercecustom-fieldsproduct-quantity

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


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.