Home > Software design >  woocommerce, loop of all products purchased by the user
woocommerce, loop of all products purchased by the user

Time:12-09

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();
        ?>

CodePudding user response:

I would suggest to start from the Order.

  1. Get all orders from User
  2. Loop through all orders from this User and create an array of all Products
  3. Then flatten the array and you can play with the product.

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)));
  • Related