2014-02-20 133 views
9

我想使用ajax刪除woocommerce購物車中的產品,而無需點擊鏈接。使用woocommerce中的ajax刪除購物車中的產品

如果遇到這種功能,請幫助我們。

add_action('wp_footer', 'add_js_to_wp_wcommerce'); 

function add_js_to_wp_wcommerce(){ ?> 
    <script type="text/javascript"> 
    jQuery('.remove-product').click(function(){ 
     var product_id = jQuery(this).attr("data-product_id"); 
     jQuery.ajax({ 
      type: 'POST', 
      dataType: 'json', 
      url: "/wp-admin/admin-ajax.php", 
      data: { action: "product_remove", 
        product_id: product_id 
      },success: function(data){ 
       console.log(data); 
      } 
     }); 
     return false; 
    }); 
    </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(); 
    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item){ 
     if($cart_item['product_id'] == $_POST['product_id']){ 
      // Remove product in the cart using cart_item_key. 
      $woocommerce->cart->get_remove_url($cart_item_key); 
     } 
    } 
    print_r($woocommerce->cart->get_cart()); 
    //echo json_encode(array('status' => 0)); 
    exit(); 
} 

回答

21

您可以使用WC_Cart set_quantity方法

而且在你的PHP做,因爲這:

$cart = WC()->instance()->cart; 
$id = $_POST['product_id']; 
$cart_id = $cart->generate_cart_id($id); 
$cart_item_id = $cart->find_product_in_cart($cart_id); 

if($cart_item_id){ 
    $cart->set_quantity($cart_item_id,0); 
} 
+0

該解決方案適用! –

+0

非常好的解決方案! – rilwis

+4

請注意,該代碼不適用於變量產品。在這種情況下,你必須將'$ variation_id'添加到函數'generate_cart_id()'或者傳遞'$ cart_id'(實際上它已經從ajax腳本正確地調用了'$ cart_item_key'。 – rassoh

1

試試這個:

foreach ($woocommerce->cart->cart_contents as $cart_item_key => $cart_item) { 

if($cart_item['product_id'] == $product_id){ 

    unset($cartdetails->cart_contents[$cart_item_key]); 

} 
} 
4

使用本:

$cart = $woocommerce->cart; 

foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item){ 
    if($cart_item['product_id'] == $_POST['product_id']){ 
     // Remove product in the cart using cart_item_key. 
     $cart->remove_cart_item($cart_item_key); 
    } 
} 
相關問題