Ashley Cameron Design

Ashley Cameron Design

Shop the Creative Design Market

Good morning

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

PHPSnippetsWordPress

About a 1 minute read

"The art of living… is neither careless drifting on the one hand nor fearful clinging to the past on the other. It consists in being sensitive to each moment, in regarding it as utterly new and unique, in having the mind open and wholly receptive."

Alan Watts

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' );