我正在try 建立一个"添加到购物车"按钮使用AJAX在WooCommerce.在这里和谷歌上搜索了几个小时后,我的问题是,我的电话可以得到200
的状态,但购物车上没有添加任何东西.我预计订单将添加到具有该类型状态的购物车中.
我在我的活动子主题的functions.php
中有以下代码:
function add_to_cart() {
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
$height = sanitize_text_field($_POST['height']);
$width = sanitize_text_field($_POST['width']);
$totalArea = sanitize_text_field($_POST['totalArea']);
$cost = sanitize_text_field($_POST['cost']);
$numPanels = intval($_POST['numPanels']);
$enteredHeight = sanitize_text_field($_POST['enteredHeight']);
$enteredWidth = sanitize_text_field($_POST['enteredWidth']);
WC()->cart->add_to_cart($product_id, $quantity, 0, array(), array('height'=>$height, 'width'=>$width, 'totalArea'=>$totalArea, 'cost'=>$cost, 'numPanels'=>$numPanels, 'enteredHeight'=>$enteredHeight, 'enteredWidth'=>$enteredWidth));
wp_die();
}
add_action('wp_ajax_add_to_cart', 'add_to_cart');
add_action('wp_ajax_nopriv_add_to_cart', 'add_to_cart');
function enqueue_add_to_cart_script() {
if(function_exists('is_product') && is_product()) {
wp_enqueue_script('add_to_cart', get_stylesheet_directory_uri() . '/js/add-to-cart-ajax.js');
wp_localize_script('add_to_cart', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ajax_nonce')));
}
}
add_action('wp_enqueue_scripts', 'enqueue_add_to_cart_script');
在我创建的子主题的js
文件夹中,我还有以下代码:
document.addEventListener('DOMContentLoaded', () => {
const ADD_TO_CART = document.getElementById('add-to-cart');
const URL = wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' );
ADD_TO_CART.addEventListener('click', (e) => {
e.preventDefault();
ADD_TO_CART.disabled = true;
const ORDER = {
action: 'add_to_cart',
quantity: 1,
product_id: '123ABC',
height: '96 in.',
width: '120 in.',
totalArea: '80 sq ft',
cost: '$636.00',
numPanels: 5,
enteredHeight: '96 in.',
enteredWidth: '120 in.',
};
fetch(URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(ORDER),
})
.then((response) => console.log('success:', response))
.catch((error) => console.error('Error:', error));
});
});
console.log('order: ', ORDER);
正在创造这个物体,正如我预期的那样.console.log('success: ', response);
返回的是200
,正如我前面所说的.
但无论如何,没有什么东西会被添加到购物车中.不管怎么说,我都想不出这件事哪里错了.有没有人看到我在这里漏掉了什么步骤(可能很简单)?
这是一个快速的"添加到购物车"按钮,任何人都可以测试一下:
<?php
function add_to_cart() { ?>
<button id="add-to-cart">Add to Cart</button>
<?php }
谢谢.