Ad

Display Product Custom Field As Order Item Meta On WooCommerce Admin Order Pages

- 1 answer

I have created my woocommerce products (fruits and vegetables) with a bunch of custom meta data I can correctly input and display them on my website. One of this data is the unit (ie kilos, box of 6, etc.).

On the Admin order page, I'd like to display this "unit" field right below the name of the products (ex : Strawberry - kilo / Eggs - box of 6, etc.).

I have tried the following code and have the following result (see screenshot) :

add_action( 'woocommerce_before_order_itemmeta', 'unit_before_order_itemmeta', 10, 3 );
function unit_before_order_itemmeta( $item_id, $item, $_product ){
        if( $unit = $_product->get_meta('unite') ) {
        echo '<p>'.$unit.'</p>';}
}

And here is the result : Screemshot single order page => The meta field 'unit' is correctly displayedunder each product, but for some reason it breaks the page and I have a critical error mesage (highlited in red) at the bottom of the page.

I have read a lot of posts here about different way to catch and display (return, print...) my meta data, but I always end up having this critical error.

Could someone help me understand what is wrong with my code?

Ad

Answer

You need to target order "line" items only and admin to avoid errors, as follow:

add_action( 'woocommerce_before_order_itemmeta', 'unit_before_order_itemmeta', 10, 3 );
function unit_before_order_itemmeta( $item_id, $item, $product ){
    // Only "line" items and backend order pages
    if( ! ( is_admin() && $item->is_type('line_item') ) ) return;

    $unit = $product->get_meta('unite');
    if( ! empty($unit) ) {
        echo '<p>'.$unit.'</p>';
    }
}

It should better work now without errors.

Ad
source: stackoverflow.com
Ad