Creating a custom search for a specific post type

To enable search on a custom post type archive, I use the pre_get_posts hook. Add this code to your theme functions.php file. Here is an example of enabling search on a post type called “resource”:

// Enable resource search
    add_action('pre_get_posts','pk_enable_resource_search', 1000);
    function pk_enable_resource_search( $query ) {

        if ( $query->is_archive('resource') && $query->is_main_query() && ! is_admin() ) {

            $search = ! empty($_GET['rs']) ? $_GET['rs'] : false;

            //Check for custom search
            if($search) {
                $query->set( 's', $_GET['rs'] );
            }
        }
    }

Then on the archive page, you’ll need to set up your search form:

<form class="archive-resource__search-form" action="<?php echo get_post_type_archive_link('resource'); ?>">
            <input type="text" placeholder="Search Resources" value="<?php echo $search_term; ?>" name="rs">
            <button type="submit" class="far fa-search"></button>
</form>

Lastly, don’t forget to look for and set your search term on your archive page. Add these variables to the top of your search form template part/archive template:

$is_search   = ! empty( $_GET['rs'] ) ? true : false;
$search_term = $is_search ? $_GET['rs'] : '';