Ashley Cameron Design

Ashley Cameron Design

Shop the Creative Design Market

Goodnight

Exclude specific or an array of posts from WordPress search results without plugin

PHPSnippetsWordPress

About a 1 minute read

"Learn from yesterday, live for today, hope for tomorrow. The important thing is not to stop questioning."

Albert Einstein

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * This function modifies the main WordPress query to remove
 * specific posts from search results.
 *
 * @param object $query The main WordPress query.
 */

function ac_exclude_post_from_search_results( $query ) {
    if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
       set_query_var('post__not_in', array( 1,2,3 ) ); //change numbers in array
    }
}
add_action( 'pre_get_posts', 'ac_exclude_post_from_search_results' );