Add Search Box for Custom Post Type Only

Hello. I am looking to see if there is some PHP snippet or other method to be able to add to my template page for a custom_post_type that will allow search of ONLY that custom_post_type.

So if I have a custom post type called "movies". I want to add a search bar within that template that will only display results on said page of movies and not another post type such as "posts" or "pages".

Thank you in advance,
David

  • David

    Kasia Swiderska Thank you for that.

    Quick question. I have created this

    <form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <input type="text" name="s" id="s" <?php if(is_search()) { ?>value="<?php the_search_query(); ?>" <?php } else { ?>value="Enter keywords &hellip;" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"<?php } ?> /><br />
    
    <?php $query_types = get_query_var('post_type'); ?>
    
    <input type="checkbox" name="post_type[]" value="wanted" <?php if (in_array('wanted', $query_types)) { echo 'checked="checked"'; } ?> /><label>Wanted</label>
    
    <input type="submit" id="searchsubmit" value="Search" />
    </form>

    But, I'm wanting to take out the checkbox and just add the default submit button submit to post_type=wanted. I don't want the check box there as we are only searching for one custom post type here.

    Any help? Thanks.

  • Patrick

    Hi there David

    I hope you don't mind me jumping in here.

    Here's a nifty snippet I've used on another project to automatically set the search results to return the same post-type as the one where the search box is located. You don't have to create any new templates, simply replace your current search form query with this one in your header.php

    You can adapt it for any post-type(s), and any templates on your site. You can see that the post-types to be returned in the results are already identified in hidden fields within:

    <?php if ((is_singular('user_guide')) || is_post_type_archive('user_guide')) { ?>
    	<form role="search" method="get" id="searchform" action="<?php bloginfo('url'); ?>" >
    	<input type="text" value="search user guide" onfocus="this.value='';" name="s" id="s" />
    	<input type="hidden" name="post_type" value="user_guide" />
    	<input type="submit" id="searchsubmit" value="" />
    	</form>
    <?php } elseif ((is_single()) || (is_archive()) || (is_search())) { ?>
    	<form role="search" method="get" id="searchform" action="<?php bloginfo('url'); ?>" >
    	<input type="text" value="search blog" onfocus="this.value='';" name="s" id="s" />
    	<input type="hidden" name="post_type" value="post" />
    	<input type="submit" id="searchsubmit" value="" />
    	</form>
    <?php } ?>

    I hope this helps, and have a great day!

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.