Getting a list of posts filtered by meta value
Let’s say we have a tech blog where we have posts talking about different tips for specific operating systems. Of course we could use taxonomies to categorize these posts by Os. But if for some reason we need to use custom meta fields we will need a way to filter our posts. In these situations we can use meta queries like shown below.
Get posts by single meta value
So we have a list of posts all with a custom field named “Os”. I used Acf to create a custom select field but this wil also works with native custom meta fields. Now we want to list all posts that are about “MacOs”. For this we can use the code snippet below.
Here we first create a new array called $args. This $args array consist of two keys. The first one is post_type we want to select. In our case we want the posts so we set this to post. This could of course also be a custom post type.
Next we set a key/value pair for meta_query. With the meta_query argument we can start selecting posts by meta key. Meta_query accepts an array of array’s each representing a specific select statement. In our case we want to select all posts where the meta field “Os” is equal to “MacOs” so we set the following key/value pairs:
- Key (Os): The name of the meta field.
- Value (MacOs): The value the meta key should have.
- Compare (=): The comparison operator to use.
Next we use the get_posts function and pass it our $args array. If all is well this should retrieve all posts where MacOs is the Os. And finaly we simply print out the results.
Note: When using the get_posts function we can also specify array keys for numberposts, category, include, exclude and suppress_filters. See the docs here.
Get posts by meta list value
If we want to show all the posts from both MacOs and Linux we can change our meta_query array like shown below.
Here instead of passing a string to the value key we pass an array containing the possible values we want to select. In our case we pass MacOs and Linux. For this to work we also have to change the compare key to ‘IN’.
The get_posts function should now get all the posts that have either a meta value of MacOs or Linux.
More to come
As you can see filtering posts with the meta_query can be pretty powerful and these code snippets only scratched the surface of what we can do. I will publish some more snippets on this topic soon.
Comments?
If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.
Follow me on twitter @Vanaf1979 or Dev.to @Vanaf1979 or subscribe to my newsletter to be notified about new articles, and other WordPress development related resources.
Thanks for reading