0

So I have been sitting here now for about three hours and I have to let this go for a few hours to grab some sleep while I hopefully get some help from you.

I have been able to get content from a database using $wpdb->get_results, and have been able to put them into an array, but I then want to use that information to run a new query inside a loop to fetch multiple items in a list.

I have used a variation of this guide https://stackoverflow.com/questions/45848249/woocommerce-get-all-orders-for-a-product to get the order ids. Now that I have them in an array, I would like to loop the array without getting a duplicate first entry. This is my current code that works, but it gives a duplicate first entry.

foreach ($orders_ids as $details) {
  $paameldingid[]=$details->order_id;
  $i=0;
  while ($order_id = $paameldingid[$i]){
$order = wc_get_order($order_id);
$fornavn = $order->get_billing_first_name();
$etternavn = $order->get_billing_last_name();
$deltakerkategori = $order->get_meta( '_billing_field_447', true );
$deltakerradio = $order->get_meta( '_billing_field_538', true );
echo ''.$fornavn.' '.$etternavn.' '.$deltakerkategori.'/'.$deltakerradio.'<br>';
 $i++; 
 }
}   

Working example: http://www.va24.no/paameldinger.php

1 Answer 1

1

That's because you're looping twice due to the while. Completely unecessary.

foreach ($orders_ids as $details) {
    $order = wc_get_order($details->order_id);
    $fornavn = $order->get_billing_first_name();
    $etternavn = $order->get_billing_last_name();
    $deltakerkategori = $order->get_meta( '_billing_field_447', true );
    $deltakerradio = $order->get_meta( '_billing_field_538', true );
    echo ''.$fornavn.' '.$etternavn.' '.$deltakerkategori.'/'.$deltakerradio.'<br>';
}

Additionally, if that doesn't fix it due to...well, magic, try this patch:

foreach( array_unique( $order_ids ) as $details )

But this smells. Bad. Check your data and see where it's going wrong.

2
  • That did it! Thank you, and by the way. This code might look messy, but it's a compact way to show a list of buyers of specific products in the shop. This site is using woocommerce as a registry for participants at a convention.
    – skoen
    Jun 3, 2018 at 2:57
  • @skoen No problem. As for "compact", no, objectively speaking, it isn't. A function should only have one purpose. I see a lot of de-couple potential here, you're doing way too much in a single function for this to ever be used in any sane system.
    – coolpasta
    Jun 3, 2018 at 3:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.