How to intercept a WordPress page request

Have you ever wanted to write a plugin that sits between a request for a WordPress page (or post) and the fulfillment of that request? In order to do so, use the pre_get_postsaction hook which passes a WP Query object as a parameter to your plugin function. This action is called early in the request flow, before any headers or content has been sent to the browser. So you can probe or modify the query object in order to create your own custom behavior.

As an example, I wanted to redirect all requests that come in for http://justinsomnia.org/random/ to a random post from my blog. Note the random link in my nav bar above. Here’s how you might do that:

2 Comments

It might make sense to put the WP query inside of your if statement to check the page name before doing a database query. That way we’re not querying the database for a random post on every single page hit that isn’t to /random.