Search code examples
phpwordpresswoocommercecartwoocommerce-bookings

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.


Solution

  • 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
        )