doupu0619 2018-04-20 12:17
浏览 165
已采纳

在Woocommerce中使用AJAX刷新/更新minicart

I’m trying to add this code to my WooCommerce setup that adds a shopping cart link wherever I put the PHP and then updates it upon changing items in the cart with AJAX: https://docs.woocommerce.com/document/show-cart-contents-total/

Here are the snippets:

HTML - PHP:

<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

In functions.php file:

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    ?>
    <a class="cart-customlocation" href="<?php echo esc_url(wc_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-customlocation'] = ob_get_clean();
    return $fragments;
}

But the AJAX is not working. Is the second snippet all I need to add to the functions.php?

It feels like I should call the function and not just define it?

Or do I need to activate AJAX in general in some way to get it to work?

  • 写回答

1条回答 默认 最新

  • dongshi1934 2018-04-20 13:29
    关注

    The filter hook woocommerce_add_to_cart_fragments is missing from your function…

    To get it work, it should be:

    add_filter( 'woocommerce_add_to_cart_fragments', 'header_add_to_cart_fragment', 30, 1 );
    function header_add_to_cart_fragment( $fragments ) {
        global $woocommerce;
    
        ob_start();
    
        ?>
        <a class="cart-customlocation" href="<?php echo esc_url(wc_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-customlocation'] = ob_get_clean();
    
        return $fragments;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Untested.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?