I am doing a WordPress site and use a custom post type 'studentinfo'. I want to build a search form and search template that will retrieve only search result from the specific post type studentinfo. Is it possible?

1 Answer 1


Yes this is possible.

There are numerous ways in which you can achieve this, either by creating a custom form and workflow or by overriding the default search template in WordPress and supply a request parameter for which can be used to identify the search request and filter the post types that should be searched.

Here's how to override the WordPress search form template that gets output from using the get_search_form() function.

Create a php file called searchform.php in your theme and place the following code:

<form role="search" method="get" id="searchform"
    class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
        <label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label>
        <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" />
        <input type="submit" id="searchsubmit"
            value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />

And in your functions.php file insert the following code:

function filter_search_post_type($query) {

    if ( $query->is_search && ! is_admin() && ! empty($_GET['search_post_type']) ) {
            $query->set( 'post_type', array($_GET['search_post_type']) );

    return $query;


Where you want the search form to appear in your theme do the following:

<?php get_search_form(); ?>

Each time a search is made using the search form, we send along a hidden input value of studentinfo with a request variable name of search_post_type.

Within the pre_get_posts hook we check to see if this is a search request and if the search_post_type request variable is set and not empty. If so we proceed to set the post_type for the query to that of the value studentinfo.

The only downside to this approach is that the form will be restricted to searching for posts within the studentinfo post_type due to the hidden input value we're passing back with the request.

Alternatively instead of creating a file called searchform.php you can create a file called studentinfo-searchform.php and paste the same form code above into that file, saving it into your theme directory.

Then where you want the form to show in your template, you will call:

<?php get_template_part('studentinfo-searchform'); ?>

This will enable you to only show the search form for studentinfo when you need to and as such not effect default search ability.

Of course there are even more ways you can go about this but let's get you started with some basics methods first.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.