WordPress – how to query posts by post format

WordPress post formats have now been around for a fair bit, allowing developers to easily create an intuitive way of displaying custom fields and setting up custom front-end layouts for the end user. The codex on the matter is however a bit lacking, resulting in multiple questions on forums and QA boards being left un-answered. So here goes my attempt at explaining how to query posts, based on post format.

Default WordPress query

So the “most” basic WordPress post query would go something like this:

For the sake of this guide I’m going to assume that you are familiar with a basic WordPress query. The TLDR; of it is basically we’re querying 3 posts with the post type of “post” and are ordering them by date (in descending order). Once the arguments are defined, we’re simply executing  a regular WP_Query.

Querying posts with the normal post format

So lets say you have multiple post formats enabled on your site and you’d like to only display the 3 most recent normal posts (so posts with the normal post format). You’d want to do something like this:

The important part is this one:

We need to keep in mind that post formats are basically custom taxonomies, so the query is much the same. We’re simply stating all of the post formats that we do not wish to include under “terms” and then using the “NOT IN” operator to say “find all posts not in those taxonomies – aka formats”.

Displaying posts with the gallery post format

What we’ve done in this example, is we’ve change the “operator” to say “IN” and changed the “terms” to a post format that we wish to query for.

Please note that you can have only a single post format under terms when querying with the “IN” operator, since a post cannot have two formats at any given time.

If you wish to query for posts which have either the “gallery post format” or a “video post format”, then you’d have to do something like this:

Conclusion

This is just a brief introduction to WordPress post formats. Let me know if you have any questions in the comments below. I’ll look into expanding this “series” into more in-depth guides in the future.

Happy coding