Posted on

Excluding old content from the search

Is there a way to exclude anything before 2016 from search results?

Yes. There are two approaches to this. If you never want to see anything old in the results, it’s best to filter in indexing. Add this to your theme functions.php.

add_filter( 'relevanssi_do_not_index', 'rlv_date_filter', 10, 2 );

/**
 * Determines whether a post should be indexed or not.
 *
 * @param boolean $block   True, if the post should not be indexed.
 * @param int     $post_id The post ID that's being indexed.
 *
 * @return boolean True, if the post should not be indexed.
 */
function rlv_date_filter( $block, $post_id ) {
    if ( get_the_date( 'Y', $post_id ) < '2016' ) {
        $block = true;
    }
    return $block;
}

If, on the other hand, you only want to apply this filter in searching, you can use the WP_Query date parameters like this:

add_filter( 'relevanssi_modify_wp_query', 'rlv_date_filter' );

/**
 * Adds a date filter to the search query.
 *
 * @param WP_Query $query The query object.
 *
 * @return WP_Query The modified query object.
 */
function rlv_date_filter( $query ) {
    $date_query = array(
        'after'     => 'January 1st, 2016',
        'inclusive' => true,
    );
    $query->set( 'date_query', $date_query );
    return $query;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.