Get all Orders IDs from a product ID in Woocommerce

后端 未结 4 1869
说谎
说谎 2020-12-04 03:24

How can I get an array with Order IDs by Product ID?

I mean receive all orders where specific product is presented.

I know how to do this by MySQL, but is t

4条回答
  •  执笔经年
    2020-12-04 04:15

    I'd like to note that the above answer will return a duplicate of the order_id if the order has multiple items in it.

    E.g.

    If there was a product called "apples" with product_id=>1036

    Customer puts "apples" 3 times in their cart and purchases it, creating order_id=>555

    If I query product_id->1036, I will get array(555,555,555).

    There's probably an SQL way of doing this which may be faster, (would appreciate anyone that could add to this), otherwise I used: array_unqiue() to merge the duplicates.

    function retrieve_orders_ids_from_a_product_id( $product_id )
    {
        global $wpdb;
    
        $table_posts = $wpdb->prefix . "posts";
        $table_items = $wpdb->prefix . "woocommerce_order_items";
        $table_itemmeta = $wpdb->prefix . "woocommerce_order_itemmeta";
    
        // 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 $table_items.order_id
            FROM $table_itemmeta, $table_items, $table_posts
            WHERE  $table_items.order_item_id = $table_itemmeta.order_item_id
            AND $table_items.order_id = $table_posts.ID
            AND $table_posts.post_status IN ( $orders_statuses )
            AND $table_itemmeta.meta_key LIKE '_product_id'
            AND $table_itemmeta.meta_value LIKE '$product_id'
            ORDER BY $table_items.order_item_id DESC"
        );
        // return an array of Orders IDs for the given product ID
        $orders_ids = array_unique($orders_ids);
        return $orders_ids;
    }
    

提交回复
热议问题