简体   繁体   English

将项目添加到 woocommerce 购物车

[英]Adding item to woocommerce cart

While writing a plug-in, I'm trying to add items to a WooCommerce cart in Ajax.在编写插件时,我正在尝试将项目添加到 Ajax 中的 WooCommerce 购物车。

I've added the following lines in my main my-plugin.php我在我的主要 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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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