3
votes

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?

1
As a new user you should please get the visual quick tour (1 minute), that explains basically how StackOverFlow works. So instead using an answer as a comment, you can leave a comment below my answer in the comment zone. To finish, if the answer below answers your question, you could please accept the answer, thank you.LoicTheAztec

1 Answers

1
votes

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.