phpwordpresswoocommerceproductorders

Display product excerpt in WooCommerce order details table and sort order items based on that


Currently I'm using Woocommerce Short_Description in Details Order answer code to show the product excerpt on WooCommerce checkout page:

add_filter( 'woocommerce_order_item_name', 'add_single_excerpt_to_order_item', 10, 3 );
function add_single_excerpt_to_order_item( $item_name, $item, $is_visible ){
    $product_id = $item->get_product_id(); // Get the product Id
    $excerpt = get_the_excerpt( $product_id ); // Get the short description

    return $excerpt . $item_name ;
}

Then I try to sort the order items alphabetically, based on the product excerpt. Via How to sort WooCommerce order items alphabetically i was able to write following code:

/*
 * Filters the $order->get_items() method results to order all line items by
 * product name
 */
add_filter( 'woocommerce_order_get_items', function( $items, $order ) {

  uasort( $items, 
          function( $a, $b ) { 
            return strnatcmp( $a['excerpt'], $b['excerpt'] ); 
          }
        );

  return $items;

}, 10, 2 );

With this code I don't get any error messages, but I don't get the desired result either. Any advice how to sort excerpt by alphabetical order?


Solution

  • To display the short product description you can use:

    function filter_woocommerce_order_item_name( $item_name, $item, $is_visible ) {
        // Get the product ID
        $product_id = $item->get_product_id();
    
        // Get the short description
        $excerpt = get_the_excerpt( $product_id );
    
        // NOT empty
        if ( ! empty ($excerpt ) ) {
            return $excerpt . ' - ' . $item_name;
        }
    
        return $item_name;
    }
    add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
    

    Note: because the woocommerce_order_item_name hook is executed on multiple pages (as well as WooCommerce email notifications) you could use conditional tags


    Regarding sorting, $a['excerpt'] does not exist, you can replace it with get_the_excerpt( $a['product_id'] )

    So you get:

    function filter_woocommerce_order_get_items( $items, $order, $types ) {
        // Sort an array with a user-defined comparison function and maintain index association
        uasort( $items, function( $a, $b ) {
            // String comparisons using a "natural order" algorithm
            return strnatcmp( get_the_excerpt( $a['product_id'] ), get_the_excerpt( $b['product_id'] ) ); 
        } );
    
        return $items;
    }
    add_filter( 'woocommerce_order_get_items', 'filter_woocommerce_order_get_items', 10, 3 );