2

I'm just trying to retrieve a value of 'title_name' from get_posts and gets the error "cannot use object of type WP_post as array..." The reason I'm not using have_posts/the_posts is because I want to display the titles in reverse:

$arr = get_posts();
$arr = array_reverse($arr);
foreach ($arr as $post) {
    echo $post['post_name'];
    echo "<br/>";
}

Why can't I echo back the field 'post_name' ? Thanks in advance!

closed as off-topic by Jacob Peattie, Michael, Krzysiek Dróżdż, Nathan Johnson, Jack Johansson Apr 8 '18 at 20:29

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • 4
    Your error explains: each post inside your array is an object, not an array. Use echo $post->post_name; if you want to display the slug, or use echo $post->post_title; to display the title. – WebElaine Apr 5 '18 at 21:25
  • Is there a name for that concept? Is it an array of objects? It's just the first time I stumble upon this. Thanks again – sir-haver Apr 5 '18 at 21:39
  • 1
    Yes, it's an array of objects. :) – WebElaine Apr 6 '18 at 14:07
4

Each post is an object, which changes the syntax you need to use to access the post name:

$arr = get_posts();
$arr = array_reverse($arr);
foreach ($arr as $post) {
    echo $post->post_name;
    echo "<br/>";
}

As a side point, a slightly easier (and computationally more efficient) way to get your posts in reverse order is to use this instead of array_reverse()

$arr = get_posts(array('order'=>'ASC'));

More fun things you can do with get_posts()'s arguments can be found here and here.

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