📅  最后修改于: 2023-12-03 14:59:12.626000             🧑  作者: Mango
Ajax 是一种基于 JavaScript 和 XML 的技术,它可以实现不刷新整个页面而对页面的部分内容进行更新,从而提高用户的交互体验。在 Woocommerce 中,我们可以利用 Ajax 技术来刷新自定义迷你购物车的计数和内容,让用户在浏览商品时方便快捷地了解购物车中的商品数量和总价。
function custom_mini_cart() {
?>
<a href="<?php echo wc_get_cart_url(); ?>" class="cart-contents">
<span class="icon-cart"></span>
<span class="count"><?php echo WC()->cart->get_cart_contents_count(); ?></span>
<span class="total"><?php echo WC()->cart->get_cart_total(); ?></span>
</a>
<?php
}
jQuery(document).ready(function($) {
$(document).on('added_to_cart', function() {
$.ajax({
type: 'GET',
url: wc_add_to_cart_params.ajax_url,
data: { action: 'custom_mini_cart' },
success: function(response) {
$('.cart-contents', response).insertAfter('.cart-button');
$('.cart-total', response).insertAfter('.cart-contents .count');
$('.cart-contents .count', response).addClass('hidden-xs');
$('.cart-contents .total', response).addClass('hidden-xs');
}
});
});
});
add_action( 'wp_ajax_custom_mini_cart', 'custom_mini_cart_callback' );
add_action( 'wp_ajax_nopriv_custom_mini_cart', 'custom_mini_cart_callback' );
function custom_mini_cart_callback() {
ob_start();
custom_mini_cart();
$response['html'] = ob_get_clean();
wp_send_json_success( $response );
}
//创建自定义迷你购物车
function custom_mini_cart() {
?>
<a href="<?php echo wc_get_cart_url(); ?>" class="cart-contents">
<span class="icon-cart"></span>
<span class="count"><?php echo WC()->cart->get_cart_contents_count(); ?></span>
<span class="total"><?php echo WC()->cart->get_cart_total(); ?></span>
</a>
<?php
}
//ajax处理函数
add_action( 'wp_ajax_custom_mini_cart', 'custom_mini_cart_callback' );
add_action( 'wp_ajax_nopriv_custom_mini_cart', 'custom_mini_cart_callback' );
function custom_mini_cart_callback() {
ob_start();
custom_mini_cart();
$response['html'] = ob_get_clean();
wp_send_json_success( $response );
}
//JavaScript代码
jQuery(document).ready(function($) {
$(document).on('added_to_cart', function() {
$.ajax({
type: 'GET',
url: wc_add_to_cart_params.ajax_url,
data: { action: 'custom_mini_cart' },
success: function(response) {
$('.cart-contents', response).insertAfter('.cart-button');
$('.cart-total', response).insertAfter('.cart-contents .count');
$('.cart-contents .count', response).addClass('hidden-xs');
$('.cart-contents .total', response).addClass('hidden-xs');
}
});
});
});