Getting title, excerpt, category outside loop in wordpress

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Getting title, excerpt, category outside loop in wordpress

When developing your own template, I found that in some cases it is best not relying on the wordpress loop for getting information related to a specific post in our database. In some case, we just need information for just one article, so its a hassle if it needs to be in a loop. We can do this using recent_posts() and get_post() function to achieve what we need.

Getting the recent posts from a category

For example, say we need our latest (1) post from one category, using recent_posts() function we can get the recent posts, limited by one post and from one category, for example:

This will save the very last post array in the $output variable. Using this is much easier and we can then play with it however we wish, but here’s another tricky part. Since we are no longer in the loop of wordpress, we can’t use the excerpt function provided by them, In this case, we need to get the post content and make ourselves a little excerpt. I haven’t seen any other options beside this so if someone has another idea, please comment and share!

Getting the post excerpt manually

So basically, using the above recent post array, we will use the bellow code further to get ourselves a little excerpt:

So that’s how we get the excerpt, unfortunately there is no other way since wordpress removed the option to use the excerpt function on a specific post ID.

Next would be to get the other information from the post, like title, category and more, a complete list from get_post() function can be found here.

For title we can use the recent option, which is:

or we can just use:

For categories you can also use something similar, only due to one article could be set in multiple categories, you have to loop the array.

Well you can get almost anything from there. WordPress now also have the option to use direct SQL queries using the new WP_Query but I’m not really fond of this, basically if you are not carefully you could create some massive load using WP_Query on your blog.

That’s it for now, don’t forget to share if you like it and comment bellow if you think there is a better option.

Request an article ←