I have WordPress 5.6.1 + WooCommerce 4.9.2
I created a function to add product into cart with Ajax. My function is very specific as I create a new tailored product and then added to cart.
First I had issue to authorize this ajax call for non connected users. This is corrected but now I have issue :
- First product is correctly added to cart
- Next products are not added to cart (but created correctly)
Can you have a look on my code?
- I force Ajax Call otherwise not working for non connected users
function forceAjaxCall(){ function forceit(){ if(isset($_REQUEST['action']) && $_REQUEST['action']=='create_product_sdwc'): do_action( 'wp_ajax_' . $_REQUEST['action'] ); do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ); endif; } add_action('wp_loaded', 'forceit'); }
My ajax function
function odc_create_product_sdwc() { ob_start(); global $woocommerce; $product = new WC_Product(); $d = new DateTime(); $product->set_props( array( 'name' => "Produit test", 'featured' => false, 'catalog_visibility' => 'hidden', 'description' => "ma Description", 'short_description' => 'Transparence : ', 'regular_price' => 10, 'sale_price' => 10, [....] ) ); $productId = $product->save(); $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $productId, 1 ); error_log("passed_validation " . $passed_validation); $reponse = $woocommerce->cart->add_to_cart($productId, 1); error_log("added to cart : key " . $reponse); error_log("added to cart : ID " . $productId); do_action( 'woocommerce_ajax_added_to_cart', $productId ); wp_die();
}