Search code examples
phpwordpresswoocommercecartwoocommerce-bookings

Get the person type name from cart items in Woocommerce Bookings


I have enabled Woocommerce Bookings plugin and I should need to display person types on the checkout page which are added into cart.

I can calculate persons count via this code:

foreach(WC()->cart->get_cart() as $cart_item) { 
    $person = array_sum( $cart_item['booking']['_persons'] );
}

But I need to display person type names.

How can I get those person type names?


If I add your code in a for loop, it only takes just one person type name. For example, I have 4 person types like Adults, Teenagers, Children, and Infants. It writes only Infants.

for ( $i = 0; $i < $person; $i++) {
    $counter = $i + 1;

    $html .= " . $person_name . "; // Here

    $html .= woocommerce_form_field( "participant_details[$i][full_name]", array(
        "type" => "text",
        "return" => true,
        "value" => "",
        "class"         => array('form-row-first'),
        "required"      => false,
        "placeholder"       => __('Name')
        )
    );
}

Solution

  • To get the person name in cart items for bookable products from Woocommerce Bookings use the following code:

    foreach(WC()->cart->get_cart() as $cart_item) {
        // The item persons count
        $person = array_sum( $cart_item['booking']['_persons'] );
    
        // Get the instance of the WC_Product_Booking product
        $booking = new WC_Product_Booking( $cart_item['product_id'] );
    
        // Loop through persons array to get the person names
        foreach ( $cart_item['booking']['_persons'] as $person_id => $person_qty ) {
            $person_name = $booking->get_person_types()[$person_id]->get_name();
        }
    }
    

    Tested and works.