简体   繁体   中英

Replace WooCommerce Cart Qty by persons count for Bookable Products

I am using the following code to update the Cart page for Qty with Persons for Booking Products:

// Add "Persons" to replace cart quantity for bookable products
add_filter( 'woocommerce_cart_item_quantity', 'replace_cart_quantity_for_bookings', 20, 3 );
function replace_cart_quantity_for_bookings( $product_quantity, $cart_item_key, $cart_item ){
    // Check that is a bookable product
    if( isset($cart_item['booking']) ){
        $product_quantity  = '<span style="text-align: center; display:inline-block;">'.$cart_item['booking']['Persons'].'<br>
        <small>(' . __('persons','woocommerce') . ')</small><span>';
    }
    return $product_quantity;
}

But this code is not working and displays that error:

Notice: Undefined index: Persons in /home/www/wp-content/themes/my-child-theme/functions.php

Some help will be appreciated.

The correct way to get cart item persons count for a bookable product is to use:

$cart_item['booking']['_qty']

So in your code:

add_filter( 'woocommerce_cart_item_quantity', 'replace_cart_quantity_for_bookings', 20, 3 );
function replace_cart_quantity_for_bookings( $quantity, $cart_item_key, $cart_item ){
    // Only for bookable product items
    if( isset($cart_item['booking']) && isset($cart_item['booking']['_qty']) ){
        $quantity  = '<span style="text-align:center; display:inline-block; line-height:10px">'.$cart_item['booking']['_qty'].'<br>
        <small>(' . __('persons','woocommerce') . ')</small><span>';
    }

    return $quantity;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


Now to get the cart item count by person type for a bookable product is (gives an array):

$cart_item['booking']['_persons']

that will give an array like for 2 different person types in the case below:

Array (
        [872] => 2
        [873] => 2
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM