如何将购物车项目和总计合并 [英] How to ajaxify cart items and total
问题描述
我有一个网站,每当有人单击添加到购物车"时,我都想通过ajax更新其购物车项目和总计.我在我的wordpress的function.php中使用下面的代码
I have a website and I want to update its cart items and total via ajax every time someone clicks on "add to cart". I am using the code below in my wordpress's function.php
add_filter('wp_nav_menu_items','sk_wcmenucart', 10, 2);
function sk_wcmenucart($menu, $args) {
// Check if WooCommerce is active and add a new item to a menu assigned to Primary Navigation Menu location
if ( !in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || 'primary' !== $args->theme_location )
return $menu;
ob_start();
global $woocommerce;
$viewing_cart = __('View your shopping cart', 'your-theme-slug');
$start_shopping = __('Start shopping', 'your-theme-slug');
$cart_url = $woocommerce->cart->get_cart_url();
$shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
$cart_contents_count = $woocommerce->cart->cart_contents_count;
$cart_contents = sprintf(_n('%d item', '%d items', $cart_contents_count, 'your-theme-slug'), $cart_contents_count);
$cart_total = $woocommerce->cart->get_cart_total();
// Uncomment the line below to hide nav menu cart item when there are no items in the cart
// if ( $cart_contents_count > 0 ) {
if ($cart_contents_count == 0) {
$menu_item = '<li class="right"><a class="wcmenucart-contents" href="'. $shop_page_url .'" title="'. $start_shopping .'">';
} else {
$menu_item = '<li class="right"><a class="wcmenucart-contents" href="'. $cart_url .'" title="'. $viewing_cart .'">';
}
$menu_item .= '<i class="fa fa-shopping-cart"></i> ';
$menu_item .= $cart_contents.' - '. $cart_total;
$menu_item .= '</a></li>';
// Uncomment the line below to hide nav menu cart item when there are no items in the cart
// }
echo $menu_item;
$social = ob_get_clean();
return $menu . $social;
}
推荐答案
使用ob_get_clean()的想法是正确的,但您需要使用适当的钩子,例如 woocommerce_add_to_fragments
.就像您可以收集ajax使用下面的代码将数据返回到变量中,以更新购物车计数-
The idea for using ob_get_clean() is correct but you need to use proper hook which might be woocommerce_add_to_fragments
.Like you could collect the ajax returned data into a variable using a function like below code updates the cart count--
add_filter('woocommerce_add_to_cart_fragments', 'newCount');
function newCount($fr){
global $woocommerce;
$items = $woocommerce->cart->get_cart();
ob_start();
echo'<a class="cart-contents" href="'.WC()->cart-
>get_cart_url().'">'.WC()->cart->get_cart_contents_count().'</a>';
$fr['a.cart-contents'] = ob_get_clean();
return $fr;
}
然后将其缓冲到您的显示位置:
then buffer it to your place of display :
Cart total: <a class="cart-contents">WC()->cart->get_cart_contents_count()</a>
PS:您需要PHP7才能运行以上代码.
PS:You need PHP7 to run above code.
这篇关于如何将购物车项目和总计合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!