WordPress search function to search custom post types.

When you’re building WordPress themes, whether for clients, or premium themes, there are occassions where you’ll want to search other items, such as products or custom post types.

In order for WordPress to know to search custom post types, we need to modify the search filter and tell WordPress what to search.

How do we do it?

Well, this is relatively easy. We just need to add a new function in our functions.php file with the following code.

if ( ! function_exists( 'uncoverwp_search_filter' ) ) :
     * Custom search function to allow us to
     * search custom post types as well as posts
    function uncoverwp_search_filter( $query )
        // is this a search query?
        if ( $query->is_search )
                        'post', // posts
                        'custom_post_type', // custom post type
                        'another_custom_post_type' // another custom post type 

        return $query;

What this function does is check if the query is actually a search query, if so, set the post_type array to the items we want to search.

In this example, we’re telling WordPress to search post and 2 custom post types, custom_post_type and another_custom_post_type

That’s all folks! It really is that simple.


Want us to email you occasionally with our latest courses, news & updates?

We use cookies to ensure that we give you the best possible experience on our website. If you continue to use this site we will assume that you are happy with it. OK Privacy Policy