【发布时间】:2017-07-08 14:51:03
【问题描述】:
我已经构建了一个自定义 WooCommerce 购物车,您可以在其中使用 AJAX 更改数量和/或从购物车中删除商品,但它有问题,我认为这与 WooCommerce 和 WordPress 随机数的有效性有关。
问题:
当您的购物车中有产品并且您在将产品添加到购物车后至少刷新了一次页面时,它可以工作。
它不起作用当您第一次访问时,您将产品添加到购物车并尝试编辑产品的数量,或尝试删除它。
请在https://staging.noten.nl/noten/ 亲自查看 - 请在您的智能手机上查看。将产品添加到购物车,单击它并更改值(多 250 克/少 250 克/删除产品)
PHP - Nonce 创建
/*
** Theme scripts
*/
function scripts() {
// Enqueue scripts
wp_enqueue_script( 'noten-nl/js', Assets\asset_path('scripts/main.js?v=' . VERSION), ['jquery-core', 'wp-util'], null, true );
// Localize script
wp_localize_script( 'noten-nl/js', 'shop', array(
'url' => admin_url( 'admin-ajax.php' ),
'cart_more' => wp_create_nonce( 'cart-more-nonce' ),
'cart_less' => wp_create_nonce( 'cart-less-nonce' ),
'cart_delete' => wp_create_nonce( 'cart-delete-nonce' )
));
}
add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\scripts', 999 );
Javascript(调用下面的 cart_more PHP 函数)
/*
** Edit items in cart
*/
function cartAction(event) {
// Log
console.log('cartAction');
// Variables
var action = $(event.currentTarget).attr('data-action'),
product = $('.cart-products-scroll .row.active');
// Load
product.children('.cart-row-item-loading').show();
// AJAX
wp.ajax.send('cart_' + action, {
data: {
nonce: shop['cart_' + action],
id: product.attr('data-product-id'),
quantity: product.attr('data-product-quantity'),
key: product.attr('data-product-cart-item-key')
},
success: function (fragments) {
// Replace fragments
$.each(fragments, function (key, value) {
$(key).replaceWith(value);
});
},
error: function (response) {
console.log(response);
}
});
}
PHP
function cart_more() {
// Log
write_log( 'cart_more()' );
// Variables
$nonce = isset( $_POST['nonce'] ) ? $_POST['nonce'] : '';
$product_id = isset( $_POST['id'] ) ? $_POST['id'] : '';
$product_quantity = isset( $_POST['quantity'] ) ? $_POST['quantity'] : '';
// Check data
if ( wp_verify_nonce( $nonce, 'cart-more-nonce' ) && ! empty( $product_id ) && ! empty( $product_quantity ) ) {
/*
** Removed for readability
*/
// Send success
wp_send_json_success( $fragments );
} else {
// Send error
wp_send_json_error( ':\'(' );
}
}
add_action( 'wp_ajax_nopriv_cart_more', __NAMESPACE__ . '\\cart_more' );
add_action( 'wp_ajax_cart_more', __NAMESPACE__ . '\\cart_more' );
问题
为什么只有在我的购物车中添加了东西后,nonce 验证才会成功?
【问题讨论】:
-
您解决了这个问题吗?我现在也有同款
标签: wordpress woocommerce cart nonce