[英]Delete the product in the cart, if the same product added in Woocommerce
[英]WooCommerce cart product delete/update
我已將添加到購物車功能更改為包含來自一個產品頁面的兩種產品。 如果添加了兩個產品,它們都將獲得一個 bundle_id,當我從購物車中刪除時,兩個產品都會被刪除,但是當我撤消時,只有一個產品返回到購物車。 我的刪除功能:
add_action( 'woocommerce_cart_item_removed', 'cart_remove_func', 10, 2 );
function cart_remove_func($removed_cart_item_key, $cart) {
$line_item = $cart->removed_cart_contents[ $removed_cart_item_key ];
$bundle_id = $line_item[ 'bundle_id' ];
foreach( WC()->cart->get_cart() as $key => $item ){
// Check if the item to be removed 1 is in cart
if( $item['bundle_id'] == $bundle_id ){
WC()->cart->remove_cart_item($key);
}
}
}
我試圖將新刪除的項目添加到removed_cart_contents
數組中,但這似乎不起作用。
我可以將額外刪除的項目添加到removed_cart_contents
數組中,以便“撤消”將兩個產品都添加回購物車嗎?
至於購物車更新:當我使用bundle_id
更新商品的數量時,兩種產品都應設置為相同的數量。 我曾嘗試使用woocommerce_update_cart_action_cart_updated
鈎子,但我在這里所做的只是顯示一個空白頁面並刪除購物車中的所有產品(顯然不是本意)。
如何更新與更新產品具有相同 bundle_id 的產品數量?
以下可能適用於撤消,盡管我還沒有完全測試它
add_filter('woocommerce_get_undo_url', 'undo_item_link_for_bundle', 10, 2);
function undo_item_link_for_bundle($link, $key){
$cart_page_url = wc_get_cart_url();
$line_item = WC()->cart->removed_cart_contents[ $key ];
$bundle_id = $line_item[ 'bundle_id' ] ?? false;
if(!$bundle_id){
return $link;
}
foreach(WC()->cart->removed_cart_contents as $k => $v){
if($v['bundle_id'] == $bundle_id){
$keys[] = $k;
}
}
$query_args = array(
'undo_items' => implode(',', $keys),
);
return $cart_page_url ? wp_nonce_url( add_query_arg( $query_args, $cart_page_url ), 'woocommerce-cart' ) : '';
}
add_action( 'wp_loaded', 'undo_multiple_items', 20 );
function undo_multiple_items(){
if ( !isset( $_REQUEST['undo_items'] ) ) {
return;
}
wc_nocache_headers();
$nonce_value = wc_get_var( $_REQUEST['woocommerce-cart-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) );
if ( ! empty( $_GET['undo_items'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $nonce_value, 'woocommerce-cart' ) ) {
// Undo Cart Items.
$items = explode(',', $_GET['undo_items']);
foreach($items as $item){
$cart_item_key = sanitize_text_field( wp_unslash( $item ) );
WC()->cart->restore_cart_item( $cart_item_key );
}
$referer = wp_get_referer() ? remove_query_arg( array( 'undo_items', '_wpnonce' ), wp_get_referer() ) : wc_get_cart_url();
wp_safe_redirect( $referer );
exit;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.