Woocommerce:从最新订单获取数据

时间:2019-01-21 11:00:25

标签: php mysql wordpress mysqli woocommerce

到目前为止,我已经能够获得使用该命令完成的最新完成订单的ID

<?php

function get_last_order_id(){
  global $wpdb;
  $statuses = "wc-completed";

  // Getting last Order ID (max value)
  $results = $wpdb->get_col( "
      SELECT MAX(ID) FROM {$wpdb->prefix}posts
      WHERE post_type LIKE 'shop_order'
      AND post_status IN ('$statuses')
  " );
 return reset($results);
}

$latest_order_id = get_last_order_id();
echo ($latest_order_id);

但是,我不想获得ID,而是希望获得billing_first_name。有谁知道如何获得它?

2 个答案:

答案 0 :(得分:0)

尝试一下

<?php
    function get_last_order_id(){
        global $wpdb;
        $statuses = "wc-completed";

        // Getting last Order ID (max value)
        $results = $wpdb->get_row( "SELECT MAX(P.ID) ,PM.meta_value as firstname
                FROM {$wpdb->prefix}posts AS P
                INNER JOIN {$wpdb->prefix}postmeta AS PM
                ON P.ID = PM.post_id

                 WHERE P.post_type LIKE 'shop_order'
                    AND P.post_status IN ('$statuses')
                    AND PM.meta_key='_billing_first_name'" );
        return $results;
    }
    $latest_order_id = get_last_order_id(); // Last order ID
    $firstname = $latest_order_id->firstname;


    echo $firstname;

答案 1 :(得分:0)

您也可以使用连接查询,请在下面的查询中进行相同的检查。

    SELECT MAX(P.ID) ,PM.meta_value as firstname
    FROM {$wpdb->prefix}posts AS P
    INNER JOIN {$wpdb->prefix}postmeta AS PM
    ON P.ID = PM.post_id

     WHERE P.post_type LIKE 'shop_order'
        AND P.post_status IN ('$statuses')
        AND PM.meta_key='_billing_first_name'

只需用给定的查询替换您的查询。

因此,下面是完整的代码。

        <?php
        function get_last_order_id()
        {
            global $wpdb;
            $statuses = "wc-completed";

            // Getting last Order ID (max value)
            $results = $wpdb->get_col( "
                SELECT MAX(P.ID) ,PM.meta_value
                    FROM {$wpdb->prefix}posts AS P
                    INNER JOIN {$wpdb->prefix}postmeta AS PM
                    ON P.ID = PM.post_id

                     WHERE P.post_type LIKE 'shop_order'
                        AND P.post_status IN ('$statuses')
                        AND PM.meta_key='_billing_first_name'
            " );
            return reset($results);
        }

        $latest_order_id = get_last_order_id(); // Last order ID
        echo ($latest_order_id);