正如我在評論中提到的,你幾乎可以從核心WooCommerce函數中借用。
首先,這裏我們將試圖ajaxify按鈕:
<a href="http://local.wordpress.dev/checkout/" class="button test-button">bla bla</a>
其次,我們將載入我們自定義腳本,並通過它的重要變量,例如管理員Ajax和結帳的URL。
add_action('wp_enqueue_scripts', 'so_load_script', 20);
function so_load_script(){
wp_enqueue_script('so_test', plugins_url('js/test.js', __FILE__));
$i18n = array('ajax_url' => admin_url('admin-ajax.php'), 'checkout_url' => get_permalink(wc_get_page_id('checkout')));
wp_localize_script('so_test', 'SO_TEST_AJAX', $i18n);
}
現在我們將寫我們的AJAX回調,這是複製幾乎逐字從WooCommerce核心,只有一些小的修改:
add_action('wp_ajax_myajax', 'myajax_callback');
add_action('wp_ajax_nopriv_myajax', 'myajax_callback');
/**
* AJAX add to cart.
*/
function myajax_callback() {
ob_start();
//$product_id = 264;
$product_id = 34;
$quantity = 1;
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
wc_add_to_cart_message($product_id);
} else {
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)
);
wp_send_json($data);
}
die();
}
和test.js
終於內容:
jQuery(document).ready(function($){
$(".test-button").click(function(e){
e.preventDefault(); // Prevent the click from going to the link
$.ajax({
url: wc_add_to_cart_params.ajax_url,
method: 'post',
data: {
'action': 'myajax'
}
}).done(function (response) {
if(response.error != 'undefined' && response.error){
//some kind of error processing or just redirect to link
// might be a good idea to link to the single product page in case JS is disabled
return true;
} else {
window.location.href = SO_TEST_AJAX.checkout_url;
}
});
});
});
目前發生了什麼?你是否收到某種錯誤? – rnevius
不,我不知道。當我查看控制檯時,沒有發現任何警告或錯誤,這是我注意到的唯一一件事:點擊按鈕後,它會加載鏈接:example.com/checkout,而不是直接添加產品。說得通? –
友好提醒客戶可以拿出一些愚蠢的東西。作爲專業人士,我們的工作是引導他們。 :)也就是說,$(「。remove-all」)'作爲一個選擇器與''元素上的類不匹配,所以什麼都不會發生。此外,WooCommerce *具有* ajax添加到購物車功能,請參閱[這裏](https://github.com/woothemes/woocommerce/blob/master/includes/class-wc-ajax.php#L396)和[這裏] (https://github.com/woothemes/woocommerce/blob/master/assets/js/frontend/add-to-cart.js#L10)。沒有必要重新發明輪子。 – helgatheviking