Woocommerce: Get all orders for a product

后端 未结 2 1994
太阳男子
太阳男子 2021-01-02 12:38

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 pro

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 13:08

    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.

提交回复
热议问题