How to retrieve a value from get_posts()? [closed]

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!

1 Answer
1

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.

Leave a Comment