Filtering WordPress posts after a certain date

| wordpress

I wanted to make it easy to link people to a chronological view of my weekly reviews after becoming a parent, so I added this code to the functions.php in my custom WordPress theme.

function sacha_tweak_query() {
    if ($_REQUEST['after'] && preg_match('/^[-0-9]+$/', $_REQUEST['after']))  { 
        set_query_var('date_query', array('column' => 'post_date', 'after' => $_REQUEST['after'], 'inclusive' => true));
    }
    if ($_REQUEST['bulk']) {
        set_query_var('posts_per_page', -1);
    }
}

add_action('pre_get_posts', 'sacha_tweak_query');

It checks for HTTP query variables of the form after=2016-02-22 and bulk=1. If it sees an “after” filter, it updates the query to show only posts after that date. Bulk gets you all the entries on one page. (… Please use this wisely. =) )

Using the pre_get_posts action lets me make the functionality available across all the archive pages (tag, category, date) without adding special code to each of them. Neat!

You can comment with Disqus or you can e-mail me at sacha@sachachua.com.