Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

php - Woocommerce: Get all orders for a product

In the Woocommerce API I see a method wc_get_orders

WooCommerce Order Functions

In the mentioned args I do not see an argument in which I could provide a product ID or Object to limit order results only for that specific product.

Is there a way I could filter orders only for specific products?

I need to use this method since some arguments are necessary

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (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 (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 );

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...