Skip to content
Advertisement

Sort Orders IDs alphabetically based on the shipping last name in Woocommerce

I need to sort my $order_name (more specifically $order_shipping_last_name) alphabetically. I’ve tried many different basic php sort() methods, in many different places, and can’t get this to work. I’m assuming I’m missing something?

In my code, get_all_orders_that_have_a_product_variation( $product_id ); function comes from this answer code that allow to get an array of orders IDs from a variation ID…

The list is output as $variables['order_list'] near the bottom.

add_action( 'fue_before_variable_replacements', 'w_add_stuff', 10, 4);
function w_add_stuff( $var, $email_data, $fue_email, $queue_item ) {

    $product_id = 2339; 
    $orders_ids = get_all_orders_that_have_a_product_variation( $product_id );

    // Iterating through each order
    foreach( $orders_ids as $order_id ){

        // Name Data
        $order = wc_get_order($order_id);
        $order_data = $order->get_data();  
        $order_shipping_first_name = $order_data['shipping']['first_name'];
        $order_shipping_last_name = $order_data['shipping']['last_name'];
        $order_name = $order_shipping_last_name . ',' . ' ' . $order_shipping_first_name . ' ';

        // Iterating through each order item
        foreach ($order->get_items() as $item_key => $item_values){

            //Quantity Data   
            $item_data = $item_values->get_data();
            $variation_id = $item_data['variation_id'];
            $item_quantity = $item_data['quantity'];

            // Display name and quantity of specific variation only
            if ( $variation_id == $product_id ) {
                $variables['order_list'] .= $order_name . ' ' . '...' . ' ' . $item_quantity . '<br>';
            }
        }
    }
}

Advertisement

Answer

This needs to be done before in the function where you get the Orders IDs, changing a bit the included SQL query, this way:

function get_all_orders_that_have_a_product_variation( $variation_id ){
    global $wpdb;

    // Getting all Order IDs with that variation ID
    $order_ids = $wpdb->get_col( "
        SELECT DISTINCT woi.order_id
        FROM {$wpdb->prefix}woocommerce_order_items AS woi
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
        LEFT JOIN {$wpdb->prefix}postmeta AS pm ON woi.order_id = pm.post_id
        WHERE woim.meta_key LIKE '_variation_id'
        AND woim.meta_value = '$variation_id'
        AND pm.meta_key LIKE '_shipping_last_name'
        ORDER BY pm.meta_value ASC
    " );

    return $order_ids; // return the array of orders ids
}

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

The change is made on sorting the Orders IDs array using the shipping last name.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement