WordPress gives developers a number of ways to grab post content from the database. A lot has been written about the differences between using query_posts(), get_posts() and WP_Query, with WP_query being generally favored in most situations. But there is another method called get_post() which can fetch content for a single post, page or custom post object. If you want to output content from a single post object, you could technically use any 4 of these methods.
The question is, where does get_post() fit in with these other methods and what is the best way fetch the content of a single content object in the posts table?
The answer depends on your use case. Let’s say you want to show an excerpt of a specific post in your sidebar, what are the considerations? The get_post() function seems tailor made from grabbing a singular content object, which would make it a pretty obvious choice, but the other methods could also be used. When do you use what?
Ruling out get_posts() and query_posts()
If you’re just polling one object, be it a post, custom post, attachment or page and you know the post id, slug or post title of the object, we can easily rule out query_posts() as it is not a good fit. It wasn’t designed for this purpose and really is about showing multiple posts in a loop.
The difference between get_posts() and get_post() is larger than it seems. The main under-the-hood difference here is that get_posts actually uses WP_query and get_post() does not. So while we can use get_posts just fine for picking a single object, it’s not going to be as efficient as get_post() or as powerful as a custom WP_query. For that reason, let’s talk about the differences between those two.
WP_query vs get_post()
Let’s first look at a simple code example that will give you the same exact output using either method. Following along the lines of our use case example, we are grabbing a post with id 5 and displaying a title and an excerpt to that post.