在 Woocommerce 中使用 AJAX 刷新/更新微型购物车

Refresh / update minicart with AJAX in Woocommerce

我正在尝试将此代码添加到我的 WooCommerce 设置中,该设置会在我放置 PHP 的任何地方添加一个购物车 link,然后在使用 [=37 更改购物车中的商品时更新它=]: https://docs.woocommerce.com/document/show-cart-contents-total/

以下是片段:

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>

functions.php 文件中:

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;
}

但是 AJAX 不工作。我需要将第二个片段添加到 functions.php 吗?

感觉我应该调用函数而不是定义它?

或者我是否需要以某种方式激活 AJAX 才能正常工作?

您的函数中缺少过滤器挂钩 woocommerce_add_to_cart_fragments

要使其正常工作,应该是:

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;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。未经测试。

2022 年解决方案

Woocommere 使用 ajax

显示实时计数器和迷你车

首先在您想要的地方显示您的 countermini cart 内容,例如 header.php 等:

<div class="basket-item-count">
  <span class="cart-items-count">
  <?php
    echo WC()->cart->get_cart_contents_count();
  ?>
</span>
</div>

这将是您希望在购物车图标旁边显示的独立计数器。

<div class="widget_shopping_cart_content">
   <?php
     echo woocommerce_mini_cart();
   ?>
</div>

这将显示迷你购物车商品。默认情况下,woocommerce 将以片段的形式更新您的迷你购物车商品,但您需要将计数器附加到此片段,如下所示,因此请将此片段添加到您的 functions.php:

add_filter( 'woocommerce_add_to_cart_fragments', 'cart_count_fragments', 10, 1 );

function cart_count_fragments( $fragments ) {
    $fragments['div.basket-item-count'] = '<div class="basket-item-count"><span class="cart-items-count">' . WC()->cart->get_cart_contents_count() . '</span></div>';
    return $fragments;
}

请注意,class 名称很重要,它将更新为 cart-items-count class。