skip to Main Content

I have an array, $persons
When I execute: print_r($persons) I get:

(
[0] => 30131
[1] => 29763
)

The two five-digit numbers are IDs for two posts in a CPT called people

How do I iterate through the array and print the title of each post?

My best guess returns nothing:

            foreach( $persons as $person ):
                $title = get_the_title( $person->ID );
                $peopleout .= $title . ', ' ;
            endforeach;
            echo $peopleout

2

Answers


  1. Judging from your first snippet, $person inside your loop is a single value, not an object.

    That means you should change the $title = lines to this:

    $title = get_the_title($person);
    

    Also, you will currently be adding an extra comma at the end of the string. To resolve this, I would add the title to an array, then implode that array to echo the values. That would look like this;

    $peopleout = [];
    foreach( $persons as $person ):
        $peopleout[] = get_the_title($person);
    endforeach;
    echo implode(", ", $peopleout);
    
    Login or Signup to reply.
  2. $person is no object, so keep it plain as it contains the ID.

    $title = get_the_title($person);
    

    Just for fun you can do all of this as a one-liner.

    echo implode(', ', array_map(fn($id) => get_the_title($id), $persons));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search