@helgatheviking - 謝謝,我發現我發佈幾個小時後。這也提供了一個超級助手https://github.com/wp-plugins/woocommerce-ajax-add-to-cart-for-variable-products/blob/master/js/add-to-cart-variation.js.
這是我完成的解決方案,以防萬一它幫助任何人。
我將我的var_id和product_id存儲爲數據屬性和數量,並且var_name在此實例中進行了硬編碼。 .doodleVarButton是我應用於所有變量項添加到購物車鏈接的類。
的JS
jQuery(function($) {
$(document).on('click', '.doodleVarButton', function() {
var var_id = $(this).data("varid");
var product_id = $(this).data("prodid");
var data = {
action: 'woocommerce_add_to_cart_variable_rc',
product_id: product_id,
quantity: 1,
variation_id: var_id,
variation: 'quantity-attribute'
};
jQuery.post(woocommerce_params.ajax_url, data, function(response) {
var fragments = response.fragments;
if (fragments) {
$.each(fragments, function(key, value) {
$(key).replaceWith(value);
});
}
});
});
擴展WC行動(加送的functions.php)
add_action('wp_ajax_woocommerce_add_to_cart_variable_rc','woocommerce_add_to_cart_variable_rc_callback');
function woocommerce_add_to_cart_variable_rc_callback() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : apply_filters('woocommerce_stock_amount', $_POST['quantity']);
$variation_id = $_POST['variation_id'];
$variation = $_POST['variation'];
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variation )) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if (get_option('woocommerce_cart_redirect_after_add') == 'yes') {
wc_add_to_cart_message($product_id);
}
WC_AJAX::get_refreshed_fragments();
} else {
//$this->json_headers();
header('Content-Type: application/json');
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)
);
echo json_encode($data);
}
die();
}
然後 - 關鍵 - WC_AJAX :: get_refreshed_fragments調用關鍵woocommerce_header_add_to_cart_fragment功能更新您的購物車的地方。我的購物車模塊化在一個單獨的PHP文件。
只要確保$ fragments [xxx]中的'xxx'與您的購物車代碼的容器相匹配即可。
function woocommerce_header_add_to_cart_fragment($fragments) {
ob_start();
include(dirname(__FILE__) . "/../views/checkout-bar.php");
$fragments['div.checkout'] = ob_get_clean();
return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');
參見[這個答案](http://stackoverflow.com/a/27278035/383847) – helgatheviking