Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Custom Meta Data from Products to Orders items in Woocommerce

I'm trying to get the Custom Meta data of my woocommerce products to my Order Columns in my Woocommerce Admin but this code wont work on my function.php in Wordpress Theme.

// Order Get Meta for PD Number
add_action('woocommerce_add_order_item_meta','adding_custom_data_in_order_items_meta', 1, 3 );
function adding_custom_data_in_order_items_meta( $post_id, $cart_item_key ) {

    // The corresponding Product Id for the item:
    $product_id = $post_id[ 'product_id' ];
    //$pd_number = $post_id['_pd_number'];
    //$pd_number = $_POST['_pd_number'];
    $pd_number = get_post_meta( $post_id[ 'product_id' ], '_pd_number', true );

    if ( !empty($pd_number) ) 
        wc_add_order_item_meta($post_id, '_pd_number', $pd_number, true);
}

Thanks

like image 664
GravityCode Avatar asked Jan 01 '26 02:01

GravityCode


1 Answers

Since Woocommerce 3, a better hook is recommended (see this answer thread).

There is some errors in your code. Try this instead:

// Add the the product custom field as item meta data in the order
add_action( 'woocommerce_add_order_item_meta', 'pd_number_order_meta_data', 10, 3 );
function pd_number_order_meta_data( $item_id, $cart_item, $cart_item_key ) {
    // get the product custom field value
    $pd_number = get_post_meta( $cart_item[ 'product_id' ], '_pd_number', true );

    // Add the custom field value to order item meta
    if( ! empty($pd_number) )
        wc_update_order_item_meta( $item_id, '_pd_number', $pd_number );
}

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

This should works on WooCommerce versions from 2.5.x to 3+.

like image 81
LoicTheAztec Avatar answered Jan 03 '26 17:01

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!