我已經構建了一個自定義WooCommerce購物車,您可以使用AJAX更改數量和/或從您的購物車中刪除物品,但它有問題,我認爲它與WooCommerce和有效性有關的WordPress隨員。WordPress隨機數不驗證WooCommerce購物車操作
問題:
它的工作原理時,有您的購物車的產品,你刷新頁面至少一次 - 加入產品給您的車後。
它不起作用當您第一次訪問時,您會在購物車中添加產品,並嘗試編輯產品數量或嘗試刪除它。
請親自看看https://staging.noten.nl/noten/ - 請檢查您的智能手機。產品加入購物車,點擊它,並更改值(250克以上/250克以下/刪除產品)
PHP - 隨機數生成
/*
** 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');
問題
爲什麼現時驗證只增加點東西給我車後成功嗎?
你管理來解決這個問題?我現在有同樣的一個 – 2017-06-22 14:23:31