Следующий код также будет обрабатывать добавление 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 добавлен в корзину
- Товары, добавленные в корзину несколько раз
На основе: WooCommerce - обрабатывать элементы корзины отдельно, если количество превышает 1