1

While writing a plug-in, I'm trying to add items to a WooCommerce cart in Ajax.

I've added the following lines in my main my-plugin.php

add_action( 'wp_ajax_add_items_to_cart', 'ajax_add_items_to_cart' );
add_action( 'wp_ajax_nopriv_add_items_to_cart', 'ajax_add_items_to_cart' );
function ajax_add_items_to_cart() {
  global $woocommerce;
  $product_id  = absint( $_POST['product_id'] );
  $quantity = absint( $_POST['quantity'] );
  $variation = 0;
  $cart_item_data['key'] = sanitize_text_field( $_POST['key'] );
  $cart_item_data['other_data'] = sanitize_text_field( $_POST['other_data'] );
  $cart_item_key = $woocommerce->cart->add_to_cart($product_id, $quantity,  $variation, $cart_item_data);
  wp_die();
}

but the cart remains empty. Any hints?

3
  • Possible duplicate of Woocommerce Ajax add to cart programmatically Commented Oct 29, 2017 at 12:01
  • You have just forgotten the Javascript/jQuery code, as Ajax works with Javascript… See the link above (and many other threads). Commented Oct 29, 2017 at 12:14
  • In fact, I've omitted it as my test show I'm entered the function properly with the rights arguments. In fact, every thing seems to work fine with no error message except that no product lands in the cart. Commented Oct 29, 2017 at 12:19

1 Answer 1

1

OK, in fact, no issue with this code, my problem was somewhere else in the code and I was sending an unknown product_id to WooCommerce.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.