Exclude specific category posts in WordPress search results

By default, WordPress search will display relevant results from entire post content on your website. Do you want to stop specific posts from appearing in WordPress search results? This can be easily implemented using piece of custom code.

Code to exclude category in WordPress search results

1. To get started, assign specific category to all posts that you want to exclude (or hide) from appearing in WordPress search results listing.

2. Then add following code to functions.php file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

add_filter( 'pre_get_posts', 'ja_search_filter' );
/**
 * Exclude category 7 from search results.
 *
 * @since ?.?.?
 * @author Jared Atchison
 * @link https://gist.github.com/1300302
 *
 * @param WP_Query $query Existing query object
 * @return WP_Query Amended query object
 */

function ja_search_filter( $query ) {

    if ( $query->is_search && !is_admin() )
        $query->set( 'cat','-7' );

    return $query;

}

In above code, change 7 with ID of the category that you want to exclude in WordPress search results listing. Quick and simple, isn’t it? [Credit Jared Atchison]

SHARE

Speak Your Mind

*

Subscribe to our mailing list

* indicates required
Close