且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Woocommerce:获取产品的所有订单

更新时间:2023-11-30 13:12:10

已编辑此功能不存在,但可以构建.因此,下面的函数将返回给定产品 ID 的所有订单 ID 的数组,从而进行正确的 SQL 查询:

Edited This function doesn't exist, but it can be built. So the function below will return an array of all orders IDs for a given product ID, making the right SQL query:

/**
 * Get All orders IDs for a given product ID.
 *
 * @param  integer  $product_id (required)
 * @param  array    $order_status (optional) Default is 'wc-completed'
 *
 * @return array
 */
function get_orders_ids_by_product_id( $product_id, $order_status = array( 'wc-completed' ) ){
    global $wpdb;

    $results = $wpdb->get_col("
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id'
        AND order_item_meta.meta_value = '$product_id'
    ");

    return $results;
}

USAGE 1(对于给定的产品 ID 37 和默认的已完成订单状态):

USAGE 1 (for a given product ID 37 and default Completed orders status):

$orders_ids = get_orders_ids_by_product_id( 37 );

// The output (for testing)
print_r( $orders_ids );

USAGE 2(对于给定的产品 ID 37一些定义的订单状态):

USAGE 2 (for a given product ID 37 and some defined orders statuses):

// Set the orders statuses
$statuses = array( 'wc-completed', 'wc-processing', 'wc-on-hold' );

$orders_ids = get_orders_ids_by_product_id( 37, $statuses );

// The output (for testing)
print_r( $orders_ids );

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.

此代码已经过测试且有效.

This code is tested and works.