This tutorial is a follow up post from my post on how to exclude pages from WordPress search results.
In this tutorial today, we will learn how to include custom post types in WordPress search results by adding modifying the main query via the pre_get_posts
hook.
By default, custom post types are not included in the search results, so we are going to create a function that allows them to be queried and searched by WordPress.
Setting up the Function to Include Custom Post Types in WordPress Search Results
Open up your functions.php
file and paste in the following:
/**
* This function modifies the main WordPress query to include an array of
* post types instead of the default 'post' post type.
*
* @param object $query The main WordPress query.
*/
function tg_include_custom_post_types_in_search_results( $query ) {
if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
$query->set( 'post_type', array( 'post', 'movies', 'products', 'portfolio' ) );
}
}
add_action( 'pre_get_posts', 'tg_include_custom_post_types_in_search_results' );
This function is simply filtering our search results by adding new arguments to the query results. As you can see from above, the following function will return content from each of these custom post types: post
, movies
, products
and portfolio
.
Simply change and/or delete the names of the custom post types in the array to match your custom post types that you want included in your WordPress search results.
Want a WordPress website that’s secure AND fast? My friends at WP Engine are offering 3 months free on all annual plans. Click here to claim your special WP Engine offer!
There you have it – now you have included custom post types in your WordPress search results!
Hope you enjoyed the post, and don’t forget to subscribe to get access to more great WordPress content!
The post How to Include Custom Post Types in WordPress Search Results appeared first on Thomas Griffin.