dsbifvcxr458755493 2017-10-21 22:54
浏览 58
已采纳

Woocommerce - 主页上的清除购物车(登录后无法使用)

I'm trying to clear the cart on home page. I've added this part to home page head section:

 <script type='text/javascript'>      
    function clearCart() {
            jQuery.post(
                "https://abcdefgh.com/wp-admin/admin-ajax.php", 
                //ajaxurl, 
                {
                    "action": "clearcart"
                } 

            );
  console.log('its homepage bro!');
 }  
  jQuery(document).ready(function(){
    clearCart();
  });
  </script>

And, added this part to functions.php:

add_action('wp_ajax_nopriv_clearcart',function(){
    global $woocommerce;
    $woocommerce->cart->empty_cart(true);
  });

If the user is not logged in, the cart is cleared on the home page. But, if the user is logged in, it does not work although the javascript part is executed (I checked via console log.).

Why do you think it happens and how can I resolve it?

  • 写回答

1条回答 默认 最新

  • douer9399 2017-10-22 01:01
    关注

    You don't need to use Ajax for that. I just use optionally a bit of jQuery to Refresh / update related cart data (like in mini-cart):

    add_action( 'wp_footer', 'clear_the_cart_in_home_refresh' );
    function clear_the_cart_in_home_refresh(){
        // Just in home page when cart is not empty
        if( WC()->cart->is_empty() ) return;
        if( ! is_front_page() ) return;
    
        // Empty cart
        WC()->cart->empty_cart(true);
        WC()->session->set('cart', array());
    
        // Reset minicart count and update page content (if needed)
        ?>
        <script type='text/javascript'>
            jQuery(document).ready(function($){
                setTimeout(function() {
                    $('body').trigger('wc_fragment_refresh');
                    $('body').trigger('updated_wc_div');
                }, 100);
            });
        </script>
        <?php
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    Tested and works.

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

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题