[英]WooCommerce - Treat cart items separate if quantity is more than 1
[英]Separated cart items in Woocommerce when quantity is more than 1
我正在使用“ WooCommerce-如果數量大於1,請單獨處理購物車項目 ”的回答代碼,如果您使用購物車,效果很好。
但是在我的情況下,我將人們直接重定向到結帳處,因此對於在結帳處底部的購物車恢復來說,它的工作方式不同。 同樣,當產品多次添加到購物車時,它不會給出單獨的項目。
以下代碼還將處理ajax添加到購物車和相同項添加多次(+將購物車重定向到結帳) :
// Split items by their quantity units
add_action( 'woocommerce_add_to_cart', 'split_cart_items_by_quantity', 10, 6 );
function split_cart_items_by_quantity( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
if ( $quantity == 1 ) return;
// Keep the product but set its quantity to 1
WC()->cart->set_quantity( $cart_item_key, 1 );
// Loop through each unit of item quantity
for ( $i = 1; $i <= $quantity -1; $i++ ) {
// Make each quantity item unique and separated
$cart_item_data['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );
// Add each item quantity as a separated cart item
WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item_data );
}
}
// Make added cart item as a unique and separated (works with ajax add to cart too)
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data', 10, 4 );
function filter_add_cart_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
if ( ! isset($cart_item_data['unique_key']) ) {
// Make this item unique
$cart_item_data['unique_key'] = md5( microtime().rand() . "Hi Dad!" );
}
return $cart_item_data;
}
// Redirect to checkout jumping cart
add_action( 'template_redirect', 'cart_redirect_to_checkout' );
function cart_redirect_to_checkout(){
if( is_cart() ){
wp_safe_redirect( wc_get_checkout_url() );
exit();
}
}
代碼進入您的活動子主題(或活動主題)的function.php文件中。 經過測試和工作。
此代碼添加了對以下內容的支持:
- Ajax已添加到購物車中
- 相同產品多次添加到購物車
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.