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 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置