WP SITES

3095 Coded Tutorials & 297 Plugins

Return Search Results After A Specific Date

If you want to exclude older posts from your search results, you can using pre_get_posts.

The following code uses the date_query from WP_Query.

Only returns results after the 1/1/2013 using the WordPress search function.

add_filter( 'pre_get_posts', 'search_filter' );
function search_filter($query) {

if ( ! is_admin() && $query->is_main_query() ) {
    if ($query->is_search) {

$query->set( 'date_query', 
    [    [
    'after'     => 'January 1st, 2013',
    'inclusive' => true,
    ]    ] 
    );
    }
  }
}

The code works with the WordPress search function and search widget included in all WordPress installations.

Was this helpful?

Yes
No
Thanks for your feedback!

Leave a Reply