0
votes

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?

  1. 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');
}
  1. 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();
    

    }

1
I noticed that if I remove wp_die() then the product is created 4 times. I think my issue is about cache or ob_start, flush etc but can't find a solution..Olivia

1 Answers

0
votes

After hours or research I finally found the solution... The add_to_cart was correct

The issue was with the non logged users and my function forceAjaxCall()

Correct answer is :

function forceAjaxCall(){
    function forceit(){
        if(isset($_REQUEST['action']) && $_REQUEST['action']=='create_product_sdwc'){
            do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
        };
    }
    add_action('admin_init', 'forceit'); // admin_init !!!!
}