Get the total amount of orders for a given product

I'm using WooCommerce and I've been using this code :

$units_sold = get_post_meta( get_the_ID(), 'total_sales', true );

This meta returns the number of items sold. Therefore if someone buys two items, then, it returns two. And I want to get the number of orders for one product, not the number of units sold.

Do you know how can I have this number easily and in an efficient way?

Thank you

Upvotes: 1

Views: 1188

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Here is a custom function that will return the number of orders for one product. You have a $product_id as argument in it:

function get_orders_count_for_a_product( $product_id ){

    $orders = wc_get_orders( array(
        'numberposts' => -1,
        'post_type' => 'shop_order',
        'post_status' => array('wc-completed') // completed status only
    ) );

    $count_orders = 0;
    foreach($orders as $order){
        $has_product = false;
        foreach($order->get_items() as $item_values)
            if( $item_values['product_id'] == $product_id )
                $has_product = true;
        if( $has_product )
            $count_orders++;
    }
    return $count_orders;
}

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

USAGE:

// Here Product ID is 125
$the_product_id = 125; 
$number_of orders = get_orders_count_for_a_product($the_product_id);
// Output the value
echo 'Number of orders for product ID ' . $the_product_id . ' is: '. $number_of orders;

Upvotes: 3

Related Questions