Adding User Custom Field Value to Order Items Details

Save product custom field value as custom order item meta in WooCommerce

There are some mistakes in your code. Try the following:

add_action( 'woocommerce_product_options_general_product_data', 'add_admin_product_custom_field' );
function add_admin_product_custom_field() {
woocommerce_wp_text_input( array(
'id' => 'validity_field',
'label' => __( 'Ważność konta', 'waznosc' ),
'class' => 'waznosc-custom-field',
'desc_tip' => true,
'description' => __( 'Wprowadz ilosc dni waznosci konta', 'waznosc' ),
) );
}

add_action( 'woocommerce_admin_process_product_object', 'save_product_custom_field_value' );
function save_product_custom_field_value( $product ) {
$value = isset( $_POST['validity_field'] ) ? sanitize_text_field($_POST['validity_field']) : '';
$product->update_meta_data( 'validity_field', $value );
}

add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_data_to_order_item', 10, 4 );
function add_custom_data_to_order( $item, $cart_item_key, $values, $order ) {
$product = wc_get_product( $item->get_product_id() ); // The WC_Product Object (and the parent variable product object for product variations)
$value = $product->get_meta('validity_field');

if( ! empty( $value ) ) {
$item->update_meta_data( __( 'Waznosc konta', 'waznosc' ), $value );
}
}

add_action( 'woocommerce_order_status_completed', 'action_completed_order', 10, 2 );
function action_completed_order( $order_id, $order ) {
$user_id = $order->get_customer_id();
$user = $order->get_user(); // The WP_User Object (if needed)

foreach ( $order->get_items() as $item_id => $item ) {
$validity = $item->get_meta( 'validity_field' );

if ( ! empty($validity) ) {
// Do something with $validity
}
}
}

This time it should work.

Adding user custom field to the order meta-data automatically

You can use woocommerce_thankyou hook to add this user data to the order meta data:

add_action( 'woocommerce_thankyou', 'orders_from_processing_to_pending', 10, 1 );
function orders_from_processing_to_pending( $order_id ) {

if ( ! $order_id )
return;

$order = wc_get_order( $order_id );
$user_id = get_current_user_id();

//Set HERE the meta key of your custom user field
$user_meta_key = 'some_meta_key';

// Get here the user custom field (meta data) value
$user_meta_value = get_user_meta($user_id, $user_meta_key, true);

if ( ! empty($user_meta_value) )
update_post_meta($order_id, $user_meta_key, $user_meta_value);
else
return;

}

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

This code is tested and works.

After, if you want to display that value on admin edit order backend or in frontend customer view order and emails notifications, you will have to use some more code and some other hooks…

Displaying product custom fields values in the order once processed

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 clean 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:

  • Adding user custom field value to order items details

  • Add custom Product data dynamically as item meta data on the Order

  • Displaying custom product data in Order items view

How to add my custom field to the Woocommerce order process (Check out form, order details and email process)

Adding a custom field in the back-end:

This will add a new field in the Product Data section of a WooCommerce product.

 /**
* Display the custom text field
* @since 1.0.0
*/
function cfwc_create_custom_field() {
$args = array(
'id' => 'custom_text_field_title',
'label' => __( 'Custom Text Field Title', 'cfwc' ),
'class' => 'cfwc-custom-field',
'desc_tip' => true,
'description' => __( 'Enter the title of your custom text field.', 'ctwc' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'cfwc_create_custom_field' );

Hooking the custom field function:

To ensure that the custom field displays in the correct place – in this case, it’s just on the General tab – we need to hook our function to the correct action: woocommerce_product_options_general_product_data.

If you wanted to add your custom field to a different tab, you could try actions like:

  • woocommerce_product_options_inventory_product_data
  • woocommerce_product_options_shipping

Saving the custom field value

With this code, we’ve got a really simple way to add custom fields to products, using standard WooCommerce functions and actions. All we need to do know is save the value of the field when the product is updated.

/**
* Save the custom field
* @since 1.0.0
*/
function cfwc_save_custom_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['custom_text_field_title'] ) ? $_POST['custom_text_field_title'] : '';
$product->update_meta_data( 'custom_text_field_title', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'cfwc_save_custom_field' );

This function runs when the product is first published or when it’s updated. It looks for a value in our custom field, sanitises it, then saves it as product meta data using the CRUD methodology introduced to WooCommerce a few versions ago.

The function hooks to the woocommerce_process_product_meta action.

Adding custom values to the cart

Assuming the product successfully validates, it’ll get added to the WooCommerce cart object. We can add our own meta data to this object so that we can use it later in the process, e.g. on the cart and checkout pages and for orders and emails.

/**
* Add the text field as item data to the cart object
* @since 1.0.0
* @param Array $cart_item_data Cart item meta data.
* @param Integer $product_id Product ID.
* @param Integer $variation_id Variation ID.
* @param Boolean $quantity Quantity
*/
function cfwc_add_custom_field_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
if( ! empty( $_POST['cfwc-title-field'] ) ) {
// Add the item data
$cart_item_data['title_field'] = $_POST['cfwc-title-field'];
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'cfwc_add_custom_field_item_data', 10, 4 );

This function hooks to woocommerce_add_cart_item_data, which filters the data passed to the cart object when a product is added to the cart. So here we check that the cfwc-title-field has a value then add that to $cart_item_data.

Displaying custom fields in the cart and checkout

Having ensured that our custom field is visible to the user in the cart and checkout forms, we now need to pass its value to the order when the user checks out.

/**
* Add custom field to order object
*/
function cfwc_add_custom_data_to_order( $item, $cart_item_key, $values, $order ) {
foreach( $item as $cart_item_key=>$values ) {
if( isset( $values['title_field'] ) ) {
$item->add_meta_data( __( 'Custom Field', 'cfwc' ), $values['title_field'], true );
}
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'cfwc_add_custom_data_to_order', 10, 4 );

We can do this very easily using the woocommerce_checkout_create_order_line_item action.

Add custom field data to WooCommerce order

Updated: compatibility with Woocommerce version 3+

You have missing the function to display this custom field value on the order edit page:

/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta( $order ){
$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
echo '<p><strong>'.__('My Field Name').':</strong> ' . get_post_meta( $order_id, 'my_field_name', true ) . '</p>';
}

On the reference link below, you have all original wooThemes functional working code snippets. It's an excellent fully functional tutorial.

Reference: [Customizing checkout fields using actions and filters][1]


Edit: Get a custom label displayed with your custom field value in Order item meta

To get a custom label like "MY field name" with your custom field value (in order items meta) instead of a slug like my_field_name, refer to this treads:

  • Saving a product custom field and displaying it in cart page
  • Displaying product custom fields values in the order once processed
  • Adding user custom field value to order items details

Passing Custom User Fields to WooCommerce Order Metadata

You don't need the meta ID in your function, so in your function code you will have:

$order->update_meta_data( 'sagecustomer', $some_value );  

But you need to get $some_value from somewhere…

This is about post meta data, but not post data, so the related database table is wp_postmeta for orders…

If the data you need come from user meta data, the code will be a bit different, like:

add_action( 'woocommerce_checkout_create_order', 'before_checkout_create_order', 10, 2 ); 
function before_checkout_create_order( $order, $data ) {
if ( $value = get_user_meta( $order->get_user_id(), 'sagecustomerid', true ) ) {
$order->update_meta_data( 'sagecustomer', $value );
}
}

Once done you will be able to get 'sagecustomer' meta value from:

  • The WC_Order Object using: $value = $order->get_meta('sagecustomer');
  • The order ID ($order_id) using: $value = get_post_meta($order_id, 'sagecustomer', true);

Getting custom field value after order completed woocommerce hook

I found the answer:
Get a custom field value saved in Order items meta in a hooked function

My working code:

add_action( 'woocommerce_order_status_completed', 'pincodeactions', 10, 1);

function pincodeactions( $order_id ) {
$order = wc_get_order( $order_id );
$order_id = $order->get_id();
$price = $order->get_total();
$billing_email = $order->get_billing_email();
$paid_date = date('Y-m-d h:m:s', strtotime($order->get_date_paid()));

//Get pin type
$order = wc_get_order($order_id);
$items = $order->get_items();

foreach ($items as $item) {
$product_id = $item['product_id'];
$pin_type = get_post_meta($product_id, 'pin_type', true);

if (empty($pin_type)){
$pin_type = 'test';
}
}

Get a custom field value saved in Order items meta in a hooked function

To get "name_on_tshirt" custom field, you need to get the order Item ID and you need to use wc_get_order_item_meta() function this way:

foreach ($order->get_items() as $item_id => $item) {
## HERE ==> Get your custom field value
$name_on_tshirt wc_get_order_item_meta( $item_id, "name_on_tshirt", true );
}

Adding Product Custom Fields to WooCommerce Completed Order Emails

To get product custom fields from an order, you need to loop through order items first and then you will be able to access and display some product custom fields as follows:

add_action( 'woocommerce_email_after_order_table', 'add_custom_field_on_completed_order_email', 20, 4 );
function add_custom_field_on_completed_order_email( $order, $sent_to_admin, $plain_text, $email ) {

if ( 'customer_completed_order' === $email->id ) :

echo '<h3>' . __("Informasi Pengambilan Barang") . '</h3>
<p class="email-upsell-p">' . __("Terima Kasih telah mengkonfirmasi pembayaran Anda, Silahkan tunjukan email ini pada saat pengambilan barang dan berikut informasi dan alamat pengambilan barang:") . '</p>';

// Loop through order items
foreach ( $order->get_items() as $item ) :

// Get the main WC_Product Object
$product = $item->get_variation_id() > 0 ? wc_get_product( $item->get_product_id() ) : $item->get_product();

// Get product custom field values
$kontak_pemberi = $product->get_meta('kontak_pemberi');
$no_hp_pemberi = $product->get_meta('no_hp_pemberi');
$nama_pemberi = $product->get_meta('nama_pemberi');

if( ! empty($kontak_pemberi) || ! empty($no_hp_pemberi) || ! empty($nama_pemberi) ) :

echo '<ul class="item ' . esc_html( $item->get_name() ) . '" style="list-style:none; margin:0 0 3em;">';

if( ! empty($kontak_pemberi) )
echo '<li>' . __("Alamat Pengambilan:") . '</strong> ' . $kontak_pemberi . '</li>';

if( ! empty($no_hp_pemberi) )
echo '<li>' . __("No. Telepon :") . '</strong> ' . $no_hp_pemberi . '</li>';

if( ! empty($nama_pemberi) )
echo '<li>' . __("Nama Pemberi Barang :") . '</strong> ' . $nama_pemberi . '</li>';

echo '</ul>';

endif;
endforeach;
endif;
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Note: since WooCommerce 3, you can use WC_Data method get_meta() on the WC_Product Object to get the custom field value(s) from its(their) meta key(s)…



Related Topics



Leave a reply



Submit