Rachit Rachit - 1 year ago 62
PHP Question

Displaying product custom fields values in the order once processed

On woocommerce, I am using the code below to render some product custom fields, on cart and on checkout:

add_filter( 'woocommerce_get_item_data', 'rendering_meta_field_on_cart_and_checkout', 10, 2 );

function rendering_meta_field_on_cart_and_checkout( $cart_data, $cart_item ) {
$custom_items = array();

if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['wccpf_enter_product_id'] ) ) {

$diamond = $cart_item['wccpf_enter_product_id'];

$pacolor = get_the_terms($diamond, 'pa_color');
foreach ( $pacolor as $pacolor ) {
$color= $pacolor ->name;
}


$custom_items[] = array( "name" => "color", "value" => $color);
}
return $custom_items;
}


How can I display that custom product fields wccpf_enter_product_id' value in orders?

Thanks.

Answer Source

You can use a custom function hooked in woocommerce_add_order_item_meta action hook to achieve this.

You will need first to add an attribute in your products to get a "readable label" for your custom field value that is going to appear as order items meta data. For that you have to create an attribute first and then set it in your product with any value (as you will replace this value in the code below).
See HERE some more explanations about that process…

You will have to replace in my code the 'custom_field_key' by your specific custom key that you will find on wp_woocommerce_order_itemmeta MySQL table for the corresponding item ID for your specific Order ID.
To find the corresponding item ID for the order, you can search in wp_woocommerce_order_items MySQL table with the Order ID…

You will have also to set your correct attribute slug instead of 'pa_your_attribute' to display in your orders the correct label text for this custom field value.
(see below other similar answers references).

So your code will be something like this:

// ADD THE INFORMATION AS META DATA SO THAT IT CAN BE SEEN AS PART OF THE ORDER
add_action('woocommerce_add_order_item_meta','add_and_update_values_to_order_item_meta', 1, 3 );
function add_and_update_values_to_order_item_meta( $item_id, $item_values, $item_key ) {

    // Getting your custom product ID value from order item meta
    $custom_value = wc_get_order_item_meta( $item_id, 'custom_field_key', true );

    // Here you update the attribute value set in your simple product
    wc_update_order_item_meta( $item_id, 'pa_your_attribute', $custom_value );
    }
}

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

This should work


Related answers:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download