Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Woocommerce display total sales per product
function dw_product_totals() {
global $wpdb;
$post = get_post( $post_id );
$current_product = get_the_ID($post);
$order_items = apply_filters( 'woocommerce_reports_top_earners_order_items', $wpdb->get_results( "
SELECT order_item_meta_2.meta_value as product_id, SUM( order_item_meta.meta_value ) as line_total 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->prefix}woocommerce_order_itemmeta as order_item_meta_2 ON order_items.order_item_id = order_item_meta_2.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( "','", array( 'wc-completed', 'wc-processing', 'wc-on-hold' ) ) . "' )
AND order_items.order_item_type = 'line_item'
AND order_item_meta.meta_key = '_line_total'
AND order_item_meta_2.meta_key = '_product_id'
GROUP BY order_item_meta_2.meta_value
" ));
$current = array($current_product);
foreach($order_items as $item) {
if(in_array($item->product_id, $current)) {
$totalDonations = $item->line_total;
}
}
$totalDonations = number_format($totalDonations, 2, '.', '');
echo 'total donations = '. $totalDonations;
}
@trbsi

This comment has been minimized.

Copy link

trbsi commented Jul 5, 2019

Isn't that COUNT( order_item_meta.meta_value ) as line_total instead of SUM( order_item_meta.meta_value ) as line_total?

@santanup789

This comment has been minimized.

Copy link

santanup789 commented Feb 13, 2020

'post_id' => $id,
Have to call the post_id as an object. But this code helped me a lot. Thanks to you bro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.