2

我正在开发一个 woocommerce 小部件,它将显示购物车小计、购物车总数、购物车项目和运输总额,它工作正常,但我想做的是每当我使用 ajax 在运输方式之间切换时更新运输总额和购物车总额. 目前,它仅在页面重新加载后自行更新。有没有可用于此目的的钩子?

4

2 回答 2

2

You can do this with the add_to_cart_fragments filter.

My implementation only updates the number of items shown with AJAX but it can be used to update totals, etc as well. This is the normal code in the template that displays the cart details:

<a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>">
(<?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count); ?>)</a>

This is the filter added in functions.php:

// Update items in cart via AJAX
add_filter('add_to_cart_fragments', 'woo_add_to_cart_ajax');
function woo_add_to_cart_ajax( $fragments ) {
    global $woocommerce;
    ob_start();
    ?>
        <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>">(<?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count); ?>)</a>
    <?php
    $fragments['a.cart-contents'] = ob_get_clean();
    return $fragments;
}

There are definitely some resources / documentation on this out there - I remember using some for reference when I wrote this code but they are a bit tough to google for.

于 2013-05-02T13:48:52.100 回答
1

对于其他对此感到疑惑的人,WooThemes 网站上有官方文档。抱歉无法在评论中发布此内容,我没有足够的声望点。

代码似乎已经更新。他们现在使用get_cart_contents_count()而不是 cart_contents_count,除其他外。

以下是更新的代码片段,直接从 WooThemes 文档复制而来(您显然可以编辑代码以显示您喜欢的任何购物车信息,但请确保在两个片段中进行相同的编辑):

要在模板中显示购物车内容和总数,请使用以下内容:

<a class="cart-contents" href="<?php echo WC()->cart->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>

要 ajaxify 您的购物车查看器,以便在添加项目时更新(通过 ajax),请使用:

<?php
// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php)
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
    ob_start();
    ?>
    <a class="cart-contents" href="<?php echo WC()->cart->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> 
    <?php

    $fragments['a.cart-contents'] = ob_get_clean();

    return $fragments;
}
于 2016-07-11T09:36:57.850 回答