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

时间:2018-03-09 00:18:41

标签: php sql wordpress woocommerce orders

我需要按字母顺序对$ order_name(更具体地说是$ order_shipping_last_name)进行排序。我已经在很多不同的地方尝试了许多不同的基本php sort()方法,并且无法实现这一点。我假设我错过了一些东西?

在我的代码中,get_all_orders_that_have_a_product_variation( $product_id );函数来自this answer code,允许从变体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>';
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这需要先在函数中获取订单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文件。经过测试和工作。

  

使用发货的姓氏对订单ID 排序进行更改。