php-从产品ID获取所有订单ID

如何获得具有按产品ID的订单ID的数组?

我的意思是收到所有展示特定产品的订单.

我知道如何通过MySQL执行此操作,但是有没有办法通过WP_Query函数执行此操作?

解决方法:

UPDATED: Changed the SQL query to "SELECT DISTINCT" instead of just "SELECT" to avoid duplicated Order IDs in the array (then no need of array_unique() to filter duplicates…).

据我所知,使用WP查询是不可能的,但是使用WordPress class wpdb可以轻松地做到这一点,包括SQL查询.

然后,您可以将其嵌入到以$product_id为参数的自定义函数中.您必须在其中设置要定位的订单状态.

因此,这是将完成此工作的函数:

function retrieve_orders_ids_from_a_product_id( $product_id ) {
    global $wpdb;

    // Define HERE the orders status to include in  <==  <==  <==  <==  <==  <==  <==
    $orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";

    # Requesting All defined statuses Orders IDs for a defined product ID
    $orders_ids = $wpdb->get_col( "
        SELECT DISTINCT woi.order_id
        FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim, 
             {$wpdb->prefix}woocommerce_order_items as woi, 
             {$wpdb->prefix}posts as p
        WHERE  woi.order_item_id = woim.order_item_id
        AND woi.order_id = p.ID
        AND p.post_status IN ( $orders_statuses )
        AND woim.meta_key LIKE '_product_id'
        AND woim.meta_value LIKE '$product_id'
        ORDER BY woi.order_item_id DESC"
    );
    // Return an array of Orders IDs for the given product ID
    return $orders_ids;
}

此代码可以在任何php文件中找到.

此代码已经过测试,可用于WooCommerce 2.5、2.6和3.0版本

用法示例:

## This will display all orders containing this product ID in a coma separated string ##

// A defined product ID: 40
$product_id = 40;

// We get all the Orders for the given product ID in an arrray
$orders_ids_array = retrieve_orders_ids_from_a_product_id( $product_id );

// We display the orders in a coma separated list
echo '<p>' . implode( ', ', $orders_ids_array ) . '</p>';
上一篇:php-如何获取Woocommerce版本ID?


下一篇:php-在Woocommerce管理订单列表中显示具有“全部”自定义状态的订单