Skip to content

Instantly share code, notes, and snippets.

@devpilot
Last active March 1, 2017 00:11
Show Gist options
  • Save devpilot/ce5db89d2459274e9f4d983595287be4 to your computer and use it in GitHub Desktop.
Save devpilot/ce5db89d2459274e9f4d983595287be4 to your computer and use it in GitHub Desktop.
Woocommerce - count specific product quantity bought by customer in all orders
<?php
/**
* Woocommerce - count specific product quantity bought by customer in all orders
*
* @param (int) $product_id
* @return int|bool
* @author devpilot
**/
function product_qty_bought($product_id){
global $post;
$count = 0;
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types(),
'post_status' => array_keys( wc_get_order_statuses()),
));
foreach ($customer_orders as $customer_order) {
if ($customer_order->post_status == "wc-processing" || $customer_order->post_status == "wc-completed") {
$order = new WC_Order($customer_order->ID);
if (count( $order->get_items()) > 0 ) {
foreach( $order->get_items() as $item ) {
if ($item['product_id'] == $product_id) {
$count = $count + $item['qty'];
}
}
}
}
}
return ($count > 0) ? $count : false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment