在Woocommerce中使用Ajax移除购物车项目后刷新购物车

时间:2018-09-26 14:01:04

标签: php jquery ajax wordpress woocommerce

我使用AJAX调用从购物车中删除/删除商品。现在,它可以正常工作,但是我需要重新加载/刷新页面以更新购物车,我在想是否可以使用更流畅的方法来完成此操作。

add_action( 'wp_footer', 'delete_item_from_cart');

function delete_item_from_cart(){ ?>
   <script>

    var ajaxdelete = {
            ajax_url: "/wp-admin/admin-ajax.php"
    };
    $('.remove-item-custom').on('click', e => {

            let currentItem = e.currentTarget;
            var product_id = $(currentItem).attr("data-product_id");
            $.ajax({
                url: ajaxdelete.ajax_url,
                type: 'POST',
                dataType: 'json',
                data: { 
                  action: "product_remove", 
                  product_id: product_id
                },success: function(data){
                    console.log('data);
                    window.location.reload(); // IS THERE A BETTER WAY??
                }
              });
            e.preventDefault();
       });
   </script>
<?php }



add_action( 'wp_ajax_product_remove', 'product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' );


function product_remove() {
  global $wpdb, $woocommerce;
  session_start();
  $cart = $woocommerce->cart;

  foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item){
      if($cart_item['product_id'] == $_POST['product_id'] ){
        $cart->remove_cart_item($cart_item_key);
  }
}
return $woocommerce->cart->get_cart();
exit();
}

因此,感谢您的帮助!必须有另一种方式...

编辑

在我的cart.php中,我有这个:

<div class="product-remove">
<?php
        echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
            '<a href="%s" class="remove remove-item-custom" aria-label="%s" data-product_id="%s" data-product_sku="%s">&times;</a>',
            esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
            __( 'Remove this item', 'woocommerce' ),
            esc_attr( $product_id ),
            esc_attr( $_product->get_sku() )
        ), $cart_item_key );
    ?>                  
</div>

0 个答案:

没有答案