简体   繁体   中英

Adding item to woocommerce cart

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?

好的,事实上,这段代码没有问题,我的问题出在代码的其他地方,我向 WooCommerce 发送了一个未知的 product_id。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM