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
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: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;$person
is no object, so keep it plain as it contains the ID.Just for fun you can do all of this as a one-liner.