Display product category names in Woocommerce order details

Tags: , , , ,



In Woocommerce, How I can display the product category names in order details (and in backend of WordPress). Also is it possible to make them appear in the email notifications.

Answer

This can be done with the following:

// Display order items product categories (Orders on front end and emails)
add_action( 'woocommerce_order_item_meta_end', 'display_custom_data_in_emails', 10, 4 );
function display_custom_data_in_emails( $item_id, $item, $order, $bool ) {
    // Get the product categories for this item
    $terms = wp_get_post_terms( $item->get_product_id(), 'product_cat', array( 'fields' => 'names' ) );

    // Output a coma separated string of product category names
    echo "<br><small>" . implode(', ', $terms) . "</small>";
}

// Display order items product categories in admin order edit pages
add_action( 'woocommerce_after_order_itemmeta', 'custom_admin_order_itemmeta', 15, 3 );
function custom_admin_order_itemmeta( $item_id, $item, $product ){
    //if( ! is_admin() ) return; // only backend

    // Target order "line items" only to avoid errors
    if( $item->is_type( 'line_item' ) ){
        // Get the product categories for this item
        $terms = wp_get_post_terms( $item->get_product_id(), 'product_cat', array( 'fields' => 'names' ) );

        // Output a coma separated string of product category names
        echo "<br><small>" . implode(', ', $terms) . "</small>";
    }
}

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



Source: stackoverflow