WooCommerce - woocommerce_add_cart_item_data

Viewed 120

I want to check if a variable product has been added. But always get an error. I have 1 product with ID = 18651, and two variations of product with id = 18652, 18653.

add_action( 'woocommerce_add_cart_item_data', function( $cart_item_data, $product_id, $variation_id) {

    if ( 18653 == $product_id ) {
        WC()->cart->add_to_cart( 15 );
    }

}, 10, 2 );

$product_id == 18653

$variation_id == 18653

Both give an error, instead of adding the product to the cart.

I would be grateful if you point out a mistake.

1 Answers
add_filter('woocommerce_add_to_cart_quantity', 'woocommerce_add_to_cart_quantity', 10, 2);

function woocommerce_add_to_cart_quantity($quantity, $product_id) {
    if (18653 == $product_id) {
        $quantity = 15;
    }
    return $quantity;
}

In this code snippet, you just need to mention parent ID for variation, when you adding a variation, the ID of parent will be passed to this filter. Tested OK

Related