Add Snippet To Project
Ever wondered if you could extend your WordPress website’s search functionality to include all types of posts, not just the standard ones? Well, WordPress provides a way to do exactly that. In this article, we will guide you on how to include all post types in your search results. By the end of this read, you’ll have a more inclusive and comprehensive search feature for your users. Let’s dive in!
function wpturbo_include_all_post_types_search($query) {
if ($query->is_search) {
$query->set('post_type', 'any');
}
return $query;
}
add_filter('pre_get_posts','wpturbo_include_all_post_types_search');
This snippet is all about altering the search functionality in WordPress to include all post types. Let’s break it down line by line.
The function wpturbo_include_all_post_types_search($query)
is defined at the start. This function accepts a single argument $query
, which is an instance of the WP_Query
class. This class is used by WordPress to query the database and retrieve post data as per the query conditions.
function wpturbo_include_all_post_types_search($query) {
Inside the function, there’s an if
statement to check if the query is a search query with $query->is_search
.
if ($query->is_search) {
If it is a search query, then $query->set('post_type', 'any');
alters the post_type
parameter of the query to any
. This means that the search will include all post types, not just the default post types (posts and pages). Instead of ‘any’, you could also specify an array of particular post types to include.
$query->set('post_type', 'any');
The processed query is then returned.
return $query;
The function is then hooked into WordPress’s pre_get_posts
filter. What this filter does is adjust the query variables before WordPress fetches posts. This means that our function wpturbo_include_all_post_types_search
will be applied to all post queries before they are run.
add_filter('pre_get_posts','wpturbo_include_all_post_types_search');
So, what we’ve done is defined a function to alter search queries and hook this function into the pre_get_posts
filter. The end result is that all searches will now return results from all post types.