Reputation: 27
I created the attached loop to be able to view all the products purchased by users. However, no duplicate products are shown. How can I change everything to show duplicate products too? Anyone big to help me? Thank you in advance.
<?php
$user_id = get_current_user_id();
$current_user = wp_get_current_user();
$customer_email = $current_user->email;
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
);
$loop = new WP_Query($args);
if ($loop->have_posts()) : while($loop->have_posts()) : $loop->the_post();
if(wc_customer_bought_product($customer_email, $user_id, get_the_ID())) {
global $product;
$id = $product->get_id();
?>
Upvotes: 1
Views: 1265
Reputation: 847
I would suggest to start from the Order.
It's also possible to get different data in the array. Check the link, in the section of the code // Get and Loop Over Order Items
Something like this. Flattening gives a nice clean array of product ids. Including duplicates. Tested on the most recent version of WooCommerce.
Note that you can also adjust the arguments for wc_get_orders to only include paid statuses. Check here for details on that.
$orders = wc_get_orders(array(
'customer_id' => get_current_user_id(),
));
// should be an array of objects
foreach($orders as $order) :
// loop through the orders
foreach ( $order->get_items() as $item_id => $item ) :
$ids[] = $item->get_product_id();
endforeach;
// add all ids in a new loop
$AllIds[] = $ids;
endforeach;
// flattens the array nicely.
$product_ids = array_merge(...array_values(($AllIds)));
Upvotes: 1