woocommerce,用户购买的所有产品的循环

woocommerce, loop of all products purchased by the user

我创建了附加循环,以便能够查看用户购买的所有产品。但是,没有显示重复的产品。我怎样才能更改所有内容以显示重复的产品?有大佬帮帮我吗?提前谢谢你。

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

我建议从订单开始。

  1. 获取用户的所有订单
  2. 遍历该用户的所有订单并创建一个包含所有产品的数组
  3. 然后把数组压平就可以玩产品了

It's also possible to get different data in the array。检查代码部分中的 link // 获取和循环订单项

像这样。扁平化提供了一个很好的干净的产品 ID 数组。包括重复项。在最新版本的 WooCommerce 上测试。

请注意,您还可以调整 wc_get_orders 的参数以仅包含付费状态。 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)));