Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remove a post type from search results, but keep all others
<?php
/**
* Modify query to remove a post type from search results, but keep all others
*
* @author Joshua David Nelson, josh@joshuadnelson.com
* @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2+
*/
add_action( 'pre_get_posts', 'jdn_modify_query' );
function jdn_modify_query( $query ) {
// First, make sure this isn't the admin and is the main query, otherwise bail
if( is_admin() || ! $query->is_main_query() )
return;
// If this is a search result query
if( $query->is_search() ) {
// Gather all searchable post types
$in_search_post_types = get_post_types( array( 'exclude_from_search' => false ) );
// The post type you're removing, in this example 'page'
$post_type_to_remove = 'page';
// Make sure you got the proper results, and that your post type is in the results
if( is_array( $in_search_post_types ) && in_array( $post_type_to_remove, $in_search_post_types ) ) {
// Remove the post type from the array
unset( $in_search_post_types[ $post_type_to_remove ] );
// set the query to the remaining searchable post types
$query->set( 'post_type', $in_search_post_types );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.