[英]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.