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 Search Results in WordPress by adding modifying the main query via the pre_get_posts hook.
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.
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 customs_post_types_in_search_results( $query ) { if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) { $query->set( 'post_type', array( 'post', 'movies', 'products', 'articles', 'portfolio' ) ); } } add_action( 'pre_get_posts', 'customs_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
, articles
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.
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!
Thanks to thomasgriffin.com