In woocommerce how to check how many times a product has been bought by a customer when the product price is 0 for last one year. To achieve this I try the bellow code and get the answer separately , the result is not shorting by product name or ID. Please help how can i short them.
Here is the code
//Check if bought it in last one year and the number of quantity
function customer_bought_qty(){
//get the value of targeted product
$_options = get_option( 'license_page_option_name' );
$ex_product_ids = $_options['ex_product_ids_warranty'];
$target_products = explode(",",$ex_product_ids); //array(18,63,85)
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed', // Only orders with status "completed"
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => '1 year ago',
)
)
) );
// Going through each orders for current customer
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order );
$order_id = $order->id;
$items = $order->get_items();
$subtotal = $order->get_subtotal(); //to check how many free item bought
//Loop trough the order items and see if it is a product we need to cehck
foreach($items as $item) {
if($subtotal== 0 && in_array($item['product_id'], $target_products)) {
$_product_id = $item['product_id'];
$_product_qty = $item['qty'];
if(isset ($_product_id)){
echo '('. get_the_title($_product_id). ')# You bought '.$_product_qty.' Times<br>';
}
}
}
}
}
The Output looks
(Product 2)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 2)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 2)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 2)# You bought 1 Times
But I need the result should be look like
(Product 2)# You bought 4 Times
(Product 1)# You bought 4 Times
to accomplish that you need a new array to store the actual quantity for each product
and when you foreach items you update this array
so your actual code should look something like:
Hope this helps!