How to modify wp_query with pre_get_posts action hook?

pre_get_posts is an action hook that runs before wp query. You can modify wp_query to using this action hook. Below are few examples:

Exclude Single Posts by ID From Home Page:

function exclude_single_posts_home($query) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'post__not_in', array( 7, 11 ) );
    }
}
add_action( 'pre_get_posts', 'exclude_single_posts_home' );

Exclude Pages from Search Results:

function search_filter($query) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ( $query->is_search ) {
            $query->set( 'post_type', 'post' );
        }
    }
}
add_action( 'pre_get_posts', 'search_filter' );

Only Display Search Results After Specific Date:

function date_search_filter($query) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ( $query->is_search ) {
            $query->set( 'date_query', array(
                array(
                    'after' => 'May 17, 2019', 
                )
            ) ); 
        }
    }
}
add_action( 'pre_get_posts', 'date_search_filter' );

Leave a Reply

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