【问题标题】:Refresh / update minicart with AJAX in Woocommerce在 Woocommerce 中使用 AJAX 刷新/更新 minicart
【发布时间】:2018-10-01 03:54:28
【问题描述】:

我正在尝试将此代码添加到我的 WooCommerce 设置中,该设置在我放置 PHP 的任何位置添加一个购物车链接,然后在使用 AJAX 更改购物车中的项目时更新它:https://docs.woocommerce.com/document/show-cart-contents-total/

这里是sn-ps:

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 不工作。我需要将第二个 sn-p 添加到 functions.php 中吗?

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

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

【问题讨论】:

    标签: php ajax wordpress woocommerce cart


    【解决方案1】:

    您的函数中缺少过滤器挂钩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 文件中。未经测试。

    【讨论】:

    • 谢谢 成功了! WooCommerce 网站的示例中缺少它。
    • 只是一个后续问题。刷新页面时是否可以重新运行该功能?我安装了 PolyLang 我使用变量更改“项目”关键字,具体取决于站点设置为瑞典语还是英语。似乎最新调用的 AJAX 以某种方式被缓存,因此更改站点的语言不会更改 header_add_to_cart_fragment 函数返回的字符串中的关键字。如果我将产品放入购物车,则关键字会更改。但是,如果我随后更改为另一种语言,则关键字仍然是我添加产品时激活的语言。
    • @tobiasg 抱歉,我从不使用 Polylang,因为我一直使用 WPML,所以对此我无能为力。
    • 购物车页面:购物车更新事件不起作用。
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2020-01-25
    • 2017-04-15
    • 2014-04-23
    • 2018-01-06
    相关资源
    最近更新 更多