Search code examples
phpwordpressforeach

Foreach loop with multiple posts is only displaying the latest in array


Problem Foreach loop is only displaying the first post of the array.

I have a WordPress get_posts query set up to fetch reviews (custom post type) assigned to the current customer, like so:

// Get all reviews 

$args = array(
  'post_type'   => 'reviews',
  'posts_per_page' => -1,
  'order'       => 'ASC',
  'orderby'     => array(
    'date' =>'DESC',
    'menu_order'=>'ASC',
  ),

  /* But only those assigned to the current customer */

  'meta_query'  => array(
    array(
      'key'     => 'customer',
      'value'       => '"'.$current_user_id.'"',
      'compare'     => 'LIKE'
    )
  )
);

$reviews = get_posts( $args );

?>

When I output echo print_r($reviews) it will print out multiple matching posts, however, when trying to display those same posts with a foreach loop it will only display the latest post in the array...

<?php foreach ( $reviews as $review ) : ?>

<li>Content is here...</li>

<?php endforeach; ?>

What am I doing wrong?


Solution

  • Can you provide more code, for example this is working:

    <?php
    
    $reviews = [
        ['name' => 'Name 1'],
        ['name' => 'Name 2'],
        ['name' => 'Name 3'],
        ['name' => 'Name 4'],
        ['name' => 'Name 5'],
    ];
    
    ?>
    
    <?php foreach ( $reviews as $review ) : ?>
    
    <li>Content is here...  <?php echo $review['name'] ?> </li>
    
    <?php endforeach; ?>