Search code examples
woocommercehook-woocommerce

Get product variation description to display on order items in woocommerce?


Following this, this and this (and many others), I still can't map each product variation description to the right order item (I'm usingproduct variations). This code displays both descriptions on both order items. How do I iterate over the ids so that the descriptions are not duplicated for each order item?

add_action( 'woocommerce_order_item_meta_end', 'add_variation_description_to_order_item', 20, 4 );
function add_variation_description_to_order_item( $item_id, $item, $order, $plain_text ) {

// for each product ordered
 foreach ( $order->get_items() as $item_id => $item  ) {
     
            $product = $item->get_product();
            $description = $product->get_description();
                  
            echo '<p>' . $description . '</p>';
    }
    
}

As you can see here descriptions are duplicated:enter image description here


Solution

  • I finally figured it out. It turns out I had to use the $order_item instead of $item in the loop, no clue why though, and of course echo outside the loop:

    add_action( 'woocommerce_order_item_meta_end', 'add_variation_description_to_order_item', 20, 4 );
    function add_variation_description_to_order_item( $item_id, $item, $order, $plain_text ) {
    
    // Loop though order "line items"
     foreach ( $order->get_items() as $item_id => $order_item ) {
            $product = $item->get_product();
            $description = $product->get_description();       
             
     }
        if ( ! empty( $description ) ) {
        echo '<br> <p>' . $description . '</p>';
        }
    }