RSS feed for Wordpress

How to Include all Post Types in WordPress search results

After WordPress 3 update, everyone started using custom post types a lot. So here is a simple snippet which will automatically include all public post types in your search results. At the same time, This snippet will also remove the custom post types that have been excluded from searches.

Include Custom Post Types in WordPress Search Results

It’s very easy to implement this hack. Just need paste the following snippet in the functions.php file of your template.

PHP Snippet

[php]

<?php
function smashing_search($query) {
if(is_search() && is_main_query()) {
$post_types = get_post_types(array(‘public’ => true, ‘exclude_from_search’ => false), ‘objects’);
$searchable_types = array();
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’, ‘smashing_search’);
?>
[/php]

Breaking the Code
PHP Snippet

[php]

$post_types = get_post_types(array(‘public’ => true, ‘exclude_from_search’ => false), ‘objects’);
[/php]

The above line is used to get all custom post types available in your blog. As you can see “Exclude_from_search” tag to be false, you can exclude certain post types which you want to hide from search results.

PHP Snippet

[php]

$searchable_types = array();
if($post_types) {
foreach( $post_types as $type) {
$searchable_types[] = $type->name;
}
}

[/php]

If any post types are present, Then an array is created “searchable_types” and each post type is stored in the array.

Now those values are passed to the function as arguments to $query.

Suggestions

Hope you liked this trick. If someone has any suggestion of reducing the above code or improving its functionality then share it with us via comments. See you soon with another cool wordpress trick.



No comments yet... Be the first to leave a reply!