Last active
December 29, 2015 01:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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