Skip to content

Instantly share code, notes, and snippets.

@robneu
Last active December 29, 2015 01:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robneu/7594551 to your computer and use it in GitHub Desktop.
Save robneu/7594551 to your computer and use it in GitHub Desktop.
Include all custom post types in front-end search results. Post types which have been set to be excluded from search will not be displayed.
<?php
add_action( 'pre_get_posts', 'prefix_include_cpts_in_search' );
/**
* Include custom post types in search results.
*
* Custom post types are not included in the default WordPress search
* functionality. This code will add them to all front-end searches.
*
* @author FAT Media, LLC
* @link http://youneedfat.com
*/
function prefix_include_cpts_in_search( $query ) {
// Do nothing if we're in the admin or not on a search query.
if ( is_admin() || ! $query->is_search ) {
return;
}
// Get all the post types which aren't excluded from search.
$post_types = get_post_types( array( 'public' => true, 'exclude_from_search' => false ), 'objects' );
$searchable_types = array();
// Get the names of the searchable post types.
if ( $post_types ) {
foreach ( $post_types as $type ) {
$searchable_types[] = $type->name;
}
}
// Set up the query.
$query->set( 'post_type', $searchable_types );
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment