3
votes

I have been looking for a solution for a while all over internet but couldn't find any proper solution. I am using several custom fields in my product page like, 'Minimum-Cooking-Time', 'Food-Availability' etc. So, I like to show this custom field's value in my cart and checkout page.

I tried snippets in function file and editing woocommerce cart file too. I have tried several codes but they are not pulling any data from my custom fields.

As you can see in the screenshot below, I want to show 'Minimum-Cooking-Time' in that black rectangular area for every product:

from the picture

I have used the following code:

add_filter( 'woocommerce_get_item_data', 'wc_add_cooking_to_cart', 10, 2 ); 
function wc_add_cooking_to_cart( $other_data, $cart_item ) { 
    $post_data = get_post( $cart_item['product_id'] );  

    echo '<br>';
    $Add = 'Cook Time: ';
    echo $test;
    $GetCookTime = get_post_meta( $post->ID, 'minimum-cooking-time', true );

    $GetCookTime = array_filter( array_map( function( $a ) {return $a[0];}, $GetCookTime ) );

    echo $Add;
    print_r( $GetCookTime );

    return $other_data; 

}

But, this shows the label 'Cook Time' but not showing any value beside it.

Any help would be appreciated.

Thank you.

1

1 Answers

7
votes

Your problem is in get_post_meta() function which last argument is set to true, so you get a custom field value as a string.
Then you are using just after the array_map() PHP function that is expecting an array but NOT a string value.

I think you don't need to use array_map() function as get_post_meta() function with last argument set to true will output a string and not an unserialized array.

Also you can set the $product_id that you are using in get_post_meta() function as first argument, in a much simple way.

So your code should work, this way:

// Render the custom product field in cart and checkout
add_filter( 'woocommerce_get_item_data', 'wc_add_cooking_to_cart', 10, 2 );
function wc_add_cooking_to_cart( $cart_data, $cart_item ) 
{
    $custom_items = array();

    if( !empty( $cart_data ) )
        $custom_items = $cart_data;

    // Get the product ID
    $product_id = $cart_item['product_id'];

    if( $custom_field_value = get_post_meta( $product_id, 'minimum-cooking-time', true ) )
        $custom_items[] = array(
            'name'      => __( 'Cook Time', 'woocommerce' ),
            'value'     => $custom_field_value,
            'display'   => $custom_field_value,
        );

    return $custom_items;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is fully functional and tested.