根据 Woocommerce 中的运输姓氏按字母顺序对订单 ID 进行排序

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

我需要按字母顺序对我的 $order_name(更具体地说是 $order_shipping_last_name)进行排序。我已经在许多不同的地方尝试了许多不同的基本 php sort() 方法,但无法使其正常工作。我假设我遗漏了什么?

在我的代码中,get_all_orders_that_have_a_product_variation( $product_id ); 函数来自 ,它允许从变体 ID 中获取 订单 ID 的数组…

列表在底部附近输出为 $variables['order_list']

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>';
            }
        }
    }
}

这需要在获取订单 ID 的函数 之前完成,稍微更改包含的 SQL 查询,这样:

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
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

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