Exclude categories from WordPress search results

Excluding a category (or categories) from the WordPress search results is easy peezy, however, that doesn’t stop most of the snippets I’ve found from doing it wrong.

<?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;
}
view raw gistfile1.aw hosted with ❤ by GitHub

Comments

  1. says

    Found solution. If it’s helpful to anyone else the code is:

    function SearchFilter($query) {
    if ($query->is_search) {
    $query->set(‘post_type’, ‘post’);
    }
    return $query;
    }

    add_filter(‘pre_get_posts’,’SearchFilter’);

Leave A Reply