Created
October 13, 2012 09:54
-
-
Save corsonr/3884007 to your computer and use it in GitHub Desktop.
Add CPTs to search
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 All Custom Post Types to search | |
* | |
* Returns the main $query. | |
* | |
* @access public | |
* @since 1.0 | |
* @return $query | |
*/ | |
function rc_add_cpts_to_search($query) { | |
// Check to verify it's search page | |
if( is_search() ) { | |
// Get post types | |
$post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects'); | |
$searchable_types = array(); | |
// Add available post types | |
if( $post_types ) { | |
foreach( $post_types as $type) { | |
$searchable_types[] = $type->name; | |
} | |
} | |
$query->set( 'post_type', $searchable_types ); | |
} | |
return $query; | |
} | |
add_action( 'pre_get_posts', 'rc_add_cpts_to_search' ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found using the builtin function
is_search()
was creating problems for other queries that are being run in some cases (in my case it was a pre-build theme).Using the method
is_search
attached to the$query
object works fine.if($query->is_search() { // stuff }