首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何对购物车项目和合计进行ajax化

如何对购物车项目和合计进行ajax化
EN

Stack Overflow用户
提问于 2017-04-30 22:00:24
回答 1查看 1.4K关注 0票数 0

我有一个网站,我想通过ajax更新其购物车项目和总额,每次有人点击“添加到购物车”。我正在我的wordpress的function.php中使用下面的代码

代码语言:javascript
复制
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;
}
EN

Stack Overflow用户

发布于 2017-04-30 22:38:26

使用ob_get_clean()的想法是正确的,但是您需要使用适当的钩子,它可以是woocommerce_add_to_fragments.Like,您可以使用如下所示的函数将ajax返回的数据收集到一个变量中,并更新购物车计数--

代码语言:javascript
复制
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;
}

然后将其缓冲到您的显示位置:

代码语言:javascript
复制
Cart total: <a class="cart-contents">WC()->cart->get_cart_contents_count()</a>

PS:你需要PHP7才能运行上面的代码。

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43707247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档