Skip to content

Instantly share code, notes, and snippets.

@thecodepoetry
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thecodepoetry/ff165afd3f9b9167971a to your computer and use it in GitHub Desktop.
Save thecodepoetry/ff165afd3f9b9167971a to your computer and use it in GitHub Desktop.
WordPress search filters
//to exclude a custom post type
function remove_portfolio_search() {
global $wp_post_types;
$wp_post_types['dt_portfolio']->exclude_from_search = true;
}
add_filter('pre_get_posts','remove_portfolio_search');
//To exclude some specific post
add_filter( 'pre_get_posts', 'cp_filter_search' );
function cp_filter_search( $query ) {
if ( $query->is_search && !is_admin() )
$query->set( 'post__not_in', array(68,11) ); //68,11 are ids of the posts to exclude
return $query;
}
//To exclude a post category
add_filter( 'pre_get_posts', 'cp_filter_search' );
function cp_filter_search( $query ) {
if ( $query->is_search && !is_admin() )
$query->set( 'cat','-3' ); // 3 is the category id
return $query;
}
//To exclude custom post type category
add_filter( 'pre_get_posts', 'cp_filter_search' );
function cp_filter_search( $query ) {
if ( $query->is_search && !is_admin() ) {
//Define the tax_query
$taxquery = array(
array(
'taxonomy' => 'dt_portfolio_category', // also try lower case, remember a taxonomy name must be in lowercase
'field' => 'slug',
'terms' => array( 'projects-2' ), //slug of the portfolio category
'operator' => 'NOT IN'
)
);
$query->set('tax_query', $taxquery );
}
}
//limit search to a specific post type
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
$query->set('post_type',array('dt_portfolio'));
}
return $query;
}
add_filter('pre_get_posts','searchfilter');
@thecodepoetry
Copy link
Author

Add thei snippet in theme's/child theme's functions.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment