Tanya Rix
Tanya Rix

Reputation: 89

Get product custom field related to Woocommerce order items

I am trying to add data from custom field in front of the subtotal on the checkout/order, but the get_post_meta is not display. I have tried $product->get_ID(), $post_id and get_the_ID().

  add_filter( 'woocommerce_order_formatted_line_subtotal', 'custom_field_test');


function bmc_test($subtotal){ 
    global $woocommerce;
    global $item_id;
    //echo $values['price_currency'];

    //just tried to see if it I could get display
    wc_get_order_item_meta($item);


    $custom_field =  get_post_meta( $values['product_id'], 'custom_field', true );
    return  $custom_field . ' '. $subtotal;
    }

Upvotes: 1

Views: 192

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253901

There is some missing arguments and some mistakes in your code… Try the following instead:

add_filter( 'woocommerce_order_formatted_line_subtotal', 'custom_field_test', 10, 3 );
function custom_field_test( $subtotal, $item, $order ){ 
    $product = $item->get_product(); // The instance of the WC_Product Object

    if( $custom_field =  get_post_meta( $product->get_id(), 'custom_field', true ) ) {
        $subtotal = $custom_field . ' '. $subtotal;
    }
    return $subtotal;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 1

Related Questions