Dynamic custom order numbers based on payment method - php

I have the following code in my functions.php file:
add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );
function change_woocommerce_order_number( $order_id ) {
$order = wc_get_order( $order_id );
//$order->get_total();
$method_of_payment = $order->get_payment_method();
if ( $method_of_payment == 'cheque' ) {
$prefix = 'CHE';
$suffix = '';
$new_order_id = $prefix . $order_id . $suffix;
return $new_order_id;
} else {
return $order_id;
}
}
The code works but I want it to permanently save the new order number. It should permanently make CHEXXXX (ex. CHE5783) the order number in the database if the user checked out using check payments. Right now this code only makes it temporary. It does not need to update previous order numbers, only new orders.

As the method WC_Order set_order_number() doesn't exist, we will add a custom field (custom meta data) when an order is placed (on order creation). Then we will get that order custom meta data in woocommerce_order_number filter hook.
The code:
add_action( 'woocommerce_checkout_update_order_meta', 'save_the_order_number', 10, 2 );
function save_the_order_number( $order_id, $data ) {
$order = wc_get_order( $order_id ); // The order Object
if ( 'cheque' === $order->get_payment_method() ) {
$prefix = 'CHE';
$suffix = '';
} else {
$prefix = '';
$suffix = '';
}
update_post_meta( $order_id, '_order_number', $prefix . $order_id . $suffix );
}
add_filter( 'woocommerce_order_number', 'set_order_number', 10, 2 );
function set_order_number( $order_id, $order ) {
// Get the order number (custom meta data)
$order_number = $order->get_meta('_order_number');
// If the order number doesn't exist (we keep that for old orders, or manual orders)
if ( empty($order_number) ) {
if ( 'cheque' === $order->get_payment_method() ) {
$prefix = 'CHE';
$suffix = '';
$order_number = $prefix . $order_id . $suffix;
} else {
$order_number = $order_id;
}
}
return $order_number;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
Now if you want to be able to edit the order number on admin order pages, use additionally the following code:
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_admin_order_order_number_custom_field' );
function display_admin_order_order_number_custom_field( $order ){
echo '<div class="edit_order_number"><p class="form-field _order_number_field" style="width:100%;">
<label for="_order_number">'. __("Order number", "woocommerce").':</label>
<input type="text" id="_order_number" name="_order_number" value="'. $order->get_order_number() .'">
</p></div>';
}
add_action( 'save_post_shop_order', 'save_admin_order_order_number_custom_field' );
function save_admin_order_order_number_custom_field( $post_id ) {
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( ! current_user_can( 'edit_shop_order', $post_id ) ) {
return;
}
// Make sure that 'shipping_date' is set.
if ( isset( $_POST['_order_number'] ) ) {
// Update custom field value
update_post_meta( $post_id, '_order_number', sanitize_text_field( $_POST['_order_number'] ) );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Related

WOOCOMMERCE call function from URL

I have a php function that creates a new session (WC()->session->set).
I want to make a link on site's header that calls a function to remove that session ( WC()->session->set( 'the_session', null );
how it should be done? couldn't find a way :(
tried to use $_get on functions, which didn't work
EDIT:
here is the code Im using, it add's the option to edit orders that have been made already:
/**
* #snippet Edit Order Functionality # WooCommerce My Account Page
* #how-to Get CustomizeWoo.com FREE
* #sourcecode https://businessbloomer.com/?p=91893
* #author Rodolfo Melogli
* #compatible WooCommerce 4.1
* #donate $9 https://businessbloomer.com/bloomer-armada/
*/
// ----------------
// 1. Allow Order Again for Processing Status
add_filter( 'woocommerce_valid_order_statuses_for_order_again', 'bbloomer_order_again_statuses' );
function bbloomer_order_again_statuses( $statuses ) {
$statuses[] = 'processing';
return $statuses;
}
// ----------------
// 2. Add Order Actions # My Account
add_filter( 'woocommerce_my_account_my_orders_actions', 'bbloomer_add_edit_order_my_account_orders_actions', 50, 2 );
function bbloomer_add_edit_order_my_account_orders_actions( $actions, $order ) {
if ( $order->has_status( 'processing' ) ) {
$actions['edit-order'] = array(
'url' => wp_nonce_url( add_query_arg( array( 'order_again' => $order->get_id(), 'edit_order' => $order->get_id() ) ), 'woocommerce-order_again' ),
'name' => __( 'שנה בחירה', 'woocommerce' )
);
}
return $actions;
}
// ----------------
// 3. Detect Edit Order Action and Store in Session
add_action( 'woocommerce_cart_loaded_from_session', 'bbloomer_detect_edit_order' );
function bbloomer_detect_edit_order( $cart ) {
if ( isset( $_GET['edit_order'], $_GET['_wpnonce'] ) && is_user_logged_in() && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), 'woocommerce-order_again' ) ) WC()->session->set( 'edit_order', absint( $_GET['edit_order'] ) );
}
// ----------------
// 4. Display Cart Notice re: Edited Order
add_action( 'woocommerce_before_cart', 'bbloomer_show_me_session' );
function bbloomer_show_me_session() {
if ( ! is_cart() ) return;
$edited = WC()->session->get('edit_order');
if ( ! empty( $edited ) ) {
$order = new WC_Order( $edited );
$credit = $order->get_total();
wc_print_notice( 'A credit of ' . wc_price($credit) . ' has been applied to this new order. Feel free to add products to it or change other details such as delivery date.', 'notice' );
}
}
// ----------------
// 5. Calculate New Total if Edited Order
add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_use_edit_order_total', 20, 1 );
function bbloomer_use_edit_order_total( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$edited = WC()->session->get('edit_order');
if ( ! empty( $edited ) ) {
$order = new WC_Order( $edited );
$credit = -1 * $order->get_total();
$cart->add_fee( 'Credit', $credit );
}
}
// ----------------
// 6. Save Order Action if New Order is Placed
add_action( 'woocommerce_checkout_update_order_meta', 'bbloomer_save_edit_order' );
function bbloomer_save_edit_order( $order_id ) {
$edited = WC()->session->get( 'edit_order' );
if ( ! empty( $edited ) ) {
// update this new order
update_post_meta( $order_id, '_edit_order', $edited );
$neworder = new WC_Order( $order_id );
$oldorder_edit = get_edit_post_link( $edited );
$neworder->add_order_note( 'Order placed after editing. Old order number: ' . $edited . '' );
// cancel previous order
$oldorder = new WC_Order( $edited );
$neworder_edit = get_edit_post_link( $order_id );
$oldorder->update_status( 'cancelled', 'Order cancelled after editing. New order number: ' . $order_id . ' -' );
WC()->session->set( 'edit_order', null );
}
}
I want to make a button on my website header, that removes the session after the user clicked "edit order", if he decided to cancel the editing and stay with his original order, the line that does that is
WC()->session->set( 'edit_order', null );
and I want it to be a link
Found the right way:
add_action('afterheader','leave_edit_order');
function after_header_block_yhm()
{
do_action( 'afterheader');
}
add_shortcode('under_header_location','after_header_block_yhm');
function leave_edit_order(){
$edited = WC()->session->get('edit_order');
if(!empty($edited) && isset($_GET['cancel_edit_order'])){
WC()->session->set( 'edit_order', null );
wc_print_notice( 'You left "edit order" session, enjoy your stay.' );
}
add_action('afterheader','leave_edit_order');
Made a new action called 'afterheader" and a new shortcode called 'under_header_location',
then used elementor to put the shortcode in the place I wanted, and then called the function in that new action I made
on the function Im checking that the user has ?cancel_edit_order on his url and then calling the function

Change WooCommerce thankyou page title based on order status

Attempting to change the title of the thank you page based on specific order statuses, by combining a filter and action as follows:
add_action( 'woocommerce_thankyou', 'order_thank_you_status' );
function order_thank_you_status( $order_id ){
// Get an instance of the `WC_Order` Object
$order = wc_get_order( $order_id );
// Get the order number
$order_number = $order->get_order_number();
// Get the order status name
$status_name = wc_get_order_status_name( $order->get_status() );
// Get the order key
$test_order_key = $order->get_order_key();
if ( $order->has_status('on-hold') || $order->has_status('mockup-requested') || $order->has_status('mockup-sent')|| $order->has_status('mockup-approved')) {
echo 'helllo world';
add_filter( 'the_title', 'woo_title_order_received', 10, 2 );
function woo_title_order_received( $title, $id ) {
if ( function_exists( 'is_order_received_page' ) &&
is_order_received_page() && get_the_ID() === $id ) {
$title = "Mockup request received";
}
return $title;
}
}
}
but I have tried multiple ways to combine the two and without any success.
You can use the following to change "Order received" page title based on order statuses:
add_action( 'the_title', 'change_order_received_page_title_based_on_order_status' );
function change_order_received_page_title_based_on_order_status( $title ){
if ( is_wc_endpoint_url('order-received') && $title === 'Order received' ) {
global $wp;
$targeted_statuses = array('on-hold', 'mockup-requested', 'mockup-sent', 'mockup-approved' );
// Get an instance of the `WC_Order` Object
$order = wc_get_order( absint($wp->query_vars['order-received']) );
if ( is_a( $order, 'WC_Order' ) && in_array( $order->get_status(), $targeted_statuses ) ) {
return __("Mockup request received", "woocommerce");
}
}
return $title;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Woocommerce after checkout redirection if order items belongs to specific product categories

I need to make it so when people press place order on our webshop, they will get redirectet to My Account, but only if the categories is XXX , XXX , XXX
But i can't seem to get it working unfortunally
I have tried using && is_product_category('Category x','Category x','Category x')
// REDIRECT AFTER PLACE ORDER BUTTON!
add_action( 'woocommerce_thankyou', 'KSVS_redirect_custom');
function KSVS_redirect_custom( $order_id ){
$order = new WC_Order( $order_id );
$url = 'https://kanselvvilselv.dk/min-konto/';
if ( $order->status != 'failed' ) {
wp_redirect($url);
exit;
}
}
It is working without putting in && is_product_category('Category x','Category x','Category x'), But then it is working on categories where it should not work.
The following code using dedicated template_redirect hook and WordPress has_term() conditional function (to be used with product categories), will redirect customers after checkout to my account section, when their order contain items from defined product categories:
add_action( 'template_redirect', 'order_received_redirection_to_my_account' );
function order_received_redirection_to_my_account() {
// Only on "Order received" page
if( is_wc_endpoint_url('order-received') ) {
global $wp;
// HERE below define your product categories in the array
$categories = array('Tshirts', 'Hoodies', 'Glasses');
$order = wc_get_order( absint($wp->query_vars['order-received']) ); // Get the Order Object
$category_found = false;
// Loop theough order items
foreach( $order->get_items() as $item ){
if( has_term( $categories, 'product_cat', $item->get_product_id() ) ) {
$category_found = true;
break;
}
}
if( $category_found ) {
// My account redirection url
$my_account_redirect_url = get_permalink( get_option('woocommerce_myaccount_page_id') );
wp_redirect( $my_account_redirect_url );
exit(); // Always exit
}
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Note: i'm not familiar with woocommerce at all, please take my answer with ease.
Seems like function is_product_category have different purpouse, by quick overview I came with this, give it a try:
$redirectWhenCategoryIs = ['cat x', 'cat y', 'cat z'];
$categories = [];
foreach($order->get_items() as $item) {
foreach(get_the_terms($item['product_id'], 'product_cat') as $term){
$categories[] = $term->slug;
}
}
if(count(array_intersect($redirectWhenCategoryIs, $categories))){
wp_redirect($url);
}
Updated, this should loop through all ordered products and if it matches 1 product with a category then it will redirect to your URL:
add_action( 'woocommerce_thankyou', 'KSVS_redirectcustom');
function KSVS_redirectcustom( $order_id ){
$order = wc_get_order( $order_id );
$url = get_permalink( get_option('woocommerce_myaccount_page_id') );
if ( $order->status != 'failed' ) {
$product_cats = array('product-cat1', 'product-cat', 'product-cat3');
foreach ($order->get_items() as $item) {
if ( has_term( $product_cats, 'product_cat', $product->id) ) {
$cat_check = true;
break;
}
}
if ( $cat_check ) {
wp_redirect($url);
exit;
}
}
}

Passing custom data from cart items to Order meta in Woocommerce 3

I have implemented a custom HTML Form and asking for some data which my customers will pass to place order successfully. Without these details my order has no importance.
For HTML form, I am referencing some custom PHP script which is below and which processes POST data from the Form and creates Cart with these data programmatically. Thanks #LoicTheAztec to help me achieve this.
The script.php file code:
<?php
require_once("../wp-load.php");
$customer_name = $_POST["customer_name"];
$customer_email = $_POST["customer_email"];
$customer_sex = $_POST["customer_sex"];
$customer_age = $_POST["customer_age"];
$product_id = $_POST["product_id"];
$custom_data = array(); // Initializing
if( isset($_POST['customer_name']) && ! empty($_POST['customer_name']) )
$custom_data['custom_data']['name'] = $_POST['customer_name'];
if( isset($_POST['customer_email']) && ! empty($_POST['customer_email']) )
$custom_data['custom_data']['email'] = $_POST['customer_email'];
if( isset($_POST['customer_sex']) && ! empty($_POST['customer_sex']) )
$custom_data['custom_data']['sex'] = $_POST['customer_sex'];
if( isset($_POST['customer_age']) && ! empty($_POST['customer_age']) )
$custom_data['custom_data']['age'] = $_POST['customer_age'];
global $woocommerce;
if (WC()->cart->add_to_cart( $product_id, '1', '0', array(), $custom_data )) {
var_dump($product_id);
} else {
var_dump($customer_name);
}
header("Location: ./checkout");
?>
As you see we have programmatically created a cart item using WC_Cart add_to_cart() method. So, all custom data is being saved to Cart as custom cart item data.
And now, we have also placed a code block into functions.php to print these data on Checkout page.
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
//var_dump($checkout);
global $woocommerce;
echo '<div id="my_custom_checkout_field"><h2>' . __('Child Info') . '</h2>';
foreach ( $woocommerce->cart->get_cart() as $cart_item ) {
if( isset($cart_item['custom_data']) ) {
$custom_data = $cart_item['custom_data'];
echo("<div>Name: <strong>" . $custom_data['name'] . "</strong></div>");
echo("<div>Email: <strong>" . $custom_data['email'] . "</strong></div>");
echo("<div>Gender: <strong>" . $custom_data['sex'] . "</strong></div>");
echo("<div>Age: <strong>" . $custom_data['age'] . "</strong></div>");
}
}
echo '</div>';
}
Now, I am trying to add these data printed on Checkout page to the Order page as well. As my order can't be completed without these data, user need to fill up these data and when he creates order, these data needs to be passed to the Order Summary page as well. And admin also needs to be able to see these data so he can process the order.
I hope this description clears everything and thanks again #LoicTheAztec to make me able to do this. Thank you very much.
Update 2 - Two steps
1) Saving data:
We will save this custom customer data as "Hidden" order "item" meta data and then as order meta data too as this is related to subscriptions with a unique order item:
// Utility function: array of custom customer key/label pairs
function custom_data_keys_labels(){
return array(
'name' => __('Customer name'), 'email' => __('Customer email'),
'sex' => __('Customer gender'), 'age' => __('Customer age'),
);
}
// Add/save custom field value as custom HIDDEN order item meta data
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_field_update_order_item_meta', 20, 4 );
function custom_field_update_order_item_meta( $item, $cart_item_key, $values, $order ) {
if ( ! isset( $values['custom_data'] ) )
return;
$custom_data = $values['custom_data'];
$meta_data = array();
$labels_keys = custom_data_keys_labels();
foreach( $labels_keys as $key => $label ){
if ( isset( $custom_data[$key] ) )
$meta_data[$key] = $custom_data[$key];
}
if ( sizeof( $meta_data ) > 0 )
$item->update_meta_data( __('_customer_data'), $meta_data );
return $cart_item_data;
}
// Add/save custom fields values as custom order meta data
add_action( 'woocommerce_checkout_create_order', 'my_custom_checkout_field_update_order_meta', 20, 2 );
function my_custom_checkout_field_update_order_meta( $order, $data ) {
$order_items = $order->get_items(); // Order itesm
$item = reset($order_items); // Keep only the first order item
$item_data = $item->get_meta( '_customer_data' ); // Get custom customer data
if( is_array($item_data) && sizeof($item_data) > 0 ){
foreach( $item_data as $key => $value ) {
if ( isset( $item_data[$key] ) )
$order->update_meta_data( '_customer_' . $key, $value );
}
// Mark as data saved
$order->update_meta_data( '_customer_data_set', true );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
2) Displaying saved custom data:
The code below also use our utility function custom_data_keys_labels()…
// Order pages (frontend and admin) display
add_filter( 'woocommerce_order_details_after_order_table' , 'display_admin_order_meta_cutom_data', 20, 1 ); // Front
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_admin_order_meta_cutom_data', 20, 1 ); // Admin
function display_admin_order_meta_cutom_data( $order ){
$labels_keys = custom_data_keys_labels();
if( $order->get_meta( '_customer_data_set' ) ){
if( is_admin() ){ // Admin
echo '<p>';
foreach( $labels_keys as $key => $label ){
if ( $order->get_meta( '_customer_' . $key ) )
echo '<strong>' . $label . ':</strong> ' . $order->get_meta( '_customer_' . $key ) . '<br>';
}
echo '</p>';
}
else { // Front end: order view and Order received (thankyou)
echo '<table class="woocommerce-table"><tbody>';
foreach( $labels_keys as $key => $label ){
if ( $order->get_meta( '_customer_' . $key ) )
echo '<tr><th>' . $label . ':</th><td>' . $order->get_meta( '_customer_' . $key ) . '</td></tr>';
}
echo '</tbody></table>';
}
}
}
// Email notifications display
add_filter( 'woocommerce_email_order_meta_fields' , 'display_email_cutom_data', 20, 3 );
function display_email_cutom_data ( $fields, $sent_to_admin, $order ) {
$labels_keys = custom_data_keys_labels();
if( $order->get_meta( '_customer_data_set' ) ){
foreach( $labels_keys as $key => $label ){
$fields['customer_' . $key] = array(
'label' => $label,
'value' => $order->get_meta( '_customer_' . $key ),
);
}
}
return $fields;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Save and display a custom field as order item meta data in WooCommerce

In woocommerce, I have maisd wome customizations and I can add a custom text field in my products, Display the values in cart and checkout (see the screenshots below).
Text field in product page:
Value in the cart:
Value in the checkout:
But I can not get it to appear in the purchase details or in the administration section (see the screenshots below).
Checkout details without the value:
Administration orders without the value:
In my code below, could someone tell what I am doing wrong?
The code that I use in my functions.php file:
// Add the field to the product
add_action('woocommerce_before_add_to_cart_button', 'my_custom_checkout_field');
function my_custom_checkout_field() {
global $product;
$id = $product->get_id();
// Get the field name of InputText1
$InputText1Name = get_post_meta($id, 'InputText1', true);
if ((!empty(get_post_meta($id, $InputText1, true)))){
echo '<div id="InputText1">';
echo '<label>'.__($InputText1Name).'</label> <input type="text" name="$InputText1V">';
echo '</div>';
}
}
// Store custom field
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['$InputText1V'] ) ) {
$cart_item_data[ '$InputText1V' ] = $_REQUEST['$InputText1V'];
/* below statement make sure every add to cart action as unique line item */
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_my_custom_checkout_field', 10, 2 );
// Render meta on cart and checkout
function render_meta_on_cart_and_checkout( $cart_data, $cart_item = null ){
// Get the product id inside the cart
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
}
// Get the field name of InputText1
$InputText1Name = get_post_meta($product_id, 'InputText1', true);
$custom_items = array();
/* Woo 2.4.2 updates */
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['$InputText1V'] ) ) {
$custom_items[] = array( "name" => $InputText1Name, "value" => $cart_item['$InputText1V'] );
}
return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
// Display as order meta
function my_field_order_meta_handler( $item_id, $values, $cart_item_key ) {
if( isset( $values['$InputText1V'] ) ) {
wc_add_order_item_meta( $product_id, "$InputText1V", $values['$InputText1V'] );
}
}
// Update the order meta with field value
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['$InputText1V']) update_post_meta( $order_id, '$InputText1Name', esc_attr($_POST['$InputText1V']));
}
// Update the user meta with field value
add_action('woocommerce_checkout_update_user_meta', 'my_custom_checkout_field_update_user_meta');
function my_custom_checkout_field_update_user_meta( $user_id ) {
if ($user_id && $_POST['$InputText1V']) update_user_meta( $user_id, '$InputText1V', esc_attr($_POST['$InputText1V']) );
}
add_filter( 'woocommerce_hidden_order_itemmeta', 'hide_order_item_meta_fields' );
// 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>'.__($InputText1V).':</strong> ' . get_post_meta( $order_id, $InputText1V, true ) . '</p>';
}
function hide_order_item_meta_fields( $fields ) {
$fields[] = 'current_view';
$fields[] = 'custom_image';//Add all meta keys to this array,so that it will not be displayed in order meta box
return $fields;
}
add_action( 'woocommerce_after_order_itemmeta', 'order_meta_customized_display',10, 3 );
function order_meta_customized_display( $item_id, $item, $product ){
$order_product_id = $item['product_id'];
$field1name = get_post_meta($order_product_id, 'InputText1', true);
echo'<br>';
print_r($InputText1V);
echo'<br>';
echo $field1name;
echo ': ';
}
There are errors and missing things in your code. You don't need all that functions too and you should really avoid to use $ (and if you can capitals) in your custom field slugs (or in key slugs and even in function names) in your code.
I have tested and revisited your code. Here is what you need and can remove everything else:
// Add the field to the product
add_action('woocommerce_before_add_to_cart_button', 'my_custom_checkout_field');
function my_custom_checkout_field() {
global $product;
$product_id = $product->get_id();
// Get the field name of InputText1
$label = get_post_meta($product_id, 'InputText1', true);
if( ! empty( $label ) ){
echo '<div id="InputText1">
<label>'.$label.':</label> <input type="text" name="custom_slug" value="">
</div>';
}
}
// Store custom field label and value in cart item data
add_filter( 'woocommerce_add_cart_item_data', 'save_my_custom_checkout_field', 10, 2 );
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['custom_slug'] ) ) {
$cart_item_data['custom_data']['label'] = get_post_meta($product_id, 'InputText1', true);
$cart_item_data['custom_data']['value'] = sanitize_text_field( $_REQUEST['custom_slug'] );
$cart_item_data['custom_data']['ukey'] = md5( microtime().rand() );
}
return $cart_item_data;
}
// Display items custom fields label and value in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
function render_meta_on_cart_and_checkout( $cart_data, $cart_item ){
$custom_items = array();
/* Woo 2.4.2 updates */
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['custom_data'] ) ) {
$custom_items[] = array(
'name' => $cart_item['custom_data']['label'],
'value' => $cart_item['custom_data']['value'],
);
}
return $custom_items;
}
// Save item custom fields label and value as order item meta data
add_action('woocommerce_add_order_item_meta','save_in_order_item_meta', 10, 3 );
function save_in_order_item_meta( $item_id, $values, $cart_item_key ) {
if( isset( $values['custom_data'] ) ) {
wc_add_order_item_meta( $item_id, $values['custom_data']['label'], $values['custom_data']['value'] );
}
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works.
This way you will get the display in Order received, Order view, Edit order (admin) and email notifications…

Categories