I’ve been working on a very simple plugin lately – more of which I’ll talk about next month – that’s serving as a demo for a larger project that I’ve been working on.
In short, the plugin gives editors the ability to exclude posts from the main index feed of the WordPress blog. This means that the blog post is still accessible via direct URL, but it won’t show up in the main feed of the site.
This is achieved by the following process:
- Introduce a meta box into the post editor dashboard
- Add a check box that gives the user the ability to check whether or not to exclude the post
- Use a hook to exclude those posts form the dashboard
It sounds easy enough, doesn’t it?
Finding Posts Without Meta Data
For the most part, it is. But when working on this particular plugin I found this familiarity with WP_Query played a huge part in being able to get some of the functionality done and I thought it might be worth sharing how both the meta data is stored and how the posts are queried before being rendered on the main index of the site.
The Meta Data
The way the meta data is stored is simple:
- If the user opts to exclude a post from the homepage, then a ‘1’ is written as a meta value to a corresponding meta key field for that specific post.
- If they opt to include the post on the homepage, then that record is deleted.
This means that there is only a record in the post meta data if the user chooses to exclude the post from the post meta data. This becomes important when we need to modify the main query.
Modifying The Main Query
Since WordPress queries all of the posts that it’s going to be displaying on its index using a main instance of the query, we need to use a specific hook for modifying the query before it’s actually ready to output the content.
Luckily, we have pre_get_posts. Straight from the Codex:
This hook is called after the query variable object is created, but before the actual query is run.
Okay, great, right? So the gist of what we need to go is to find all of the posts that do not have the associated ‘exclude’ meta data associated with them and render them to the front-end.
Notice here that we’re querying off the meta data and we’re specifically instructing WordPress to include posts that do not have the
exclude_posts_from_index meta key (which is what we were talking about earlier in this article).
So there you have it – if you’re familiar with WP_Query then you should have all you need to customize the