3
votes

need to add product to cart programatically with custom parameters

I used woocommerce_add_cart_item_data this hook to use custom item data in woocommerce session

function wdm_add_item_data($cart_item_data,$product_id)
    {

        /*Here, We are adding item in WooCommerce session with, wdm_user_custom_data_value name*/
        global $woocommerce;

        $new_value = array("option1" => $_REQUEST['option1'], "option2" => $_REQUEST['option2'], );




            if(empty($cart_item_data))
                return $new_value;
            else
                return array_merge($cart_item_data,$new_value);


        //Unset our custom session variable, as it is no longer needed.
    }
$woocommerce->cart->add_to_cart(16); i tried this code 

how to pass custom parameters in this function?

2

2 Answers

1
votes

This is what eventually got it working for me. Couldn't find many resources online so I'm posting this.

I added this code to the functions.php This will fire every time any page is loaded, but you could put a condition around it.

add_action('wp_loaded', function() {
    global $woocommerce;

    $sku = 'ABC101';
    $quantity = 20;

    $product_id = wc_get_product_id_by_sku($sku);
    $woocommerce->cart->add_to_cart($product_id, $quantity);
});
0
votes

I am using this code.

add_action('init', 'products_to_cart');
function products_to_cart(){                            
    $woocommerce->cart->add_to_cart($prod_ID, $prod_Qty);
}