Display Custom Field's Value in Woocommerce Cart & Checkout items

浪子不回头ぞ 提交于 2019-12-04 13:37:44

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!