Filtering WordPress posts after a certain date
| wordpressI 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!
1 comment
jehzlau
2016-12-30T14:32:35ZThis is a very useful code snippet. Thanks for sharing sacha! It has been a long time since I last visited your blog. Happy new year! :)