Thứ Hai, 21 tháng 5, 2018

Thay đổi woocommerce mini cart khi ấn vào add to cart bằng ajax

Sau đây sẽ là cách giúp các bạn thay đổi số lượng, tổng giá của woocommerce mini cart khi có sản phẩm được thêm vào giỏ hàng bằng ajax.
Change Mini car when add to cartThông thường khi thiết kế web bán hàng với woocommerce chúng ta sẽ có minicart trên menu hoặc header của trang. Nhưng khi khách hàng ấn thêm sản phẩm vào giỏ hàng thì nó sẽ không tự động thay đổi mà phải ấn F5 hay load lại trang thì mới thay đổi thông tin giỏ hàng. Cách dưới đây sẽ giải quyết vấn đề trên bằng cách thay đổi woocommerce mini cart ngay lập tức bằng ajax khi có sản phẩm được thêm vào giỏi hàng.

Thêm woocommerce mini cart

Thêm đoạn code sau vào bất kỹ chỗ nào bạn muốn hiển thị mini cart
1
2
3
4
5
6
<?php global $woocommerce; ?>
<a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>">
<?php
echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total();
?>
</a>

Thay đổi woocommerce mini cart bằng Ajax

Thêm đoạn code sau vào file functions.php trong theme bạn đang sử dụng là được nhé.
1
2
3
4
5
6
7
8
9
10
11
/*Woocommerce minicart*/
add_filter('woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');
function woocommerce_header_add_to_cart_fragment( $fragments ) {
 global $woocommerce;
 ob_start();
 ?>
 <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
 <?php
 $fragments['a.cart-contents'] = ob_get_clean();
 return $fragments;
}
Chúc các bạn thành công ^^

Không có nhận xét nào:
Write nhận xét