I am trying to display the 10 most sold products on my website but I am not getting the right products.
I am using the following code in order to get the relevant products:
$query = new WP_Query(array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 10,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'order' => 'DESC',
));
When I check in WooCommerce --> Reports --> Orders --> By Product
, it displays 10 different products than the products I get using the above code.
So I did a little experiment and using the following code I am printing the amount a product is sold:
echo "total_sales: " . get_post_meta( $product_id, 'total_sales', true ) . "<br>";
This code returns a different value then the value in WooCommerce --> Reports --> Orders --> By Product
. For example, I have a product with an id 555565 and in WooCommerce --> Reports --> Orders --> By Product
it says there are 47 sales of this product while get_post_meta( $product_id, 'total_sales', true )
returns 3.
Also I am using the following code (which I found on StackOverflow) in order to print all the orders which includes product 555565 and it turns out the product is included in 43 orders:
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;
}
##To conclude##
I suspect something wrong with total_sales
.
If someone knows how to solve it, I will be grateful 🙂
If any more information is needed, please let me know and I will add it.