Display custom field value in cart and Woocommerce orders

I've searched for a solution all over the internet for a while, but couldn't find a suitable solution. I use a few custom fields on my product page like "Minimum Cooking Time", "Food Availability", etc. So I like to show this custom field value in my cart and checkout page.

I tried snippets in the features file and edited the woocommerce cart file. I have tried several codes but they are not pulling data from my custom fields.

As you can see in the screenshot below, I want to display the "Minimum Cooking Time" in this black rectangular area for each product:

from image

I 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 "Cook Time" label, but doesn't show any value next to it.

Any help would be appreciated.

Thank.

+3


source to share


1 answer


Your problem is in the function for which the last argument has a value , so you will get the custom field value as a string . Then you use right after the PHP function that expects an array , but NOT a string value . get_post_meta()

true


array_map()

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

get_post_meta()

true

Also you can set which one you use as the first argument in a very simple way. $product_id

get_post_meta()

So your code should work like this:



// 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;
}

      

The code goes in the function.php file of your active child theme (or theme), as well as any plugin file.

This code is fully functional and tested.

+7


source







All Articles