Skip to content

Instantly share code, notes, and snippets.

@santanup789
Last active February 14, 2020 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santanup789/8233b8d46b0d27f32757fa0400bd9f28 to your computer and use it in GitHub Desktop.
Save santanup789/8233b8d46b0d27f32757fa0400bd9f28 to your computer and use it in GitHub Desktop.
Get total sale by product amount in woocommerce
<?php
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 '<p><label>Donation we get: </label>'. get_woocommerce_currency_symbol(). $totalDonations . '</p>';
}
?>
@santanup789
Copy link
Author

Used $post_id as an array object. Then <?php dw_product_totals($post_id); ?> paste this in your product loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment