Problem
I have a page on my site where I need to do additional searching within that page. I am using the default way of WordPress searching with <?php get_search_form(); ?>
for my main header search, which works great.
I created another HTML form on my page, not using the default PHP method, for the additional searching like so:
<form action="<?php bloginfo('siteurl'); ?>" id="searchform" method="get">
<div>
<label for="s" class="screen-reader-text">Search for:</label>
<input type="text" id="s" name="s" value="" />
<input type="hidden" name="post_type" value="photo_group" />
<input type="submit" value="Search" id="searchsubmit" />
</div>
</form>
I use the type=hidden
for getting the custom post type that I want to search through:
<input type="hidden" name="post_type" value="photo_group" />
which gives me a link that looks similar to:
http://mywebsite.com/?s=search&post_type=photo_group
Question
When I use the new search form created on the page, it uses the default search.php to display the results. How can I display the search results of the custom post type search, lets say in a div
on the same page?
I’ve tried creating a new page template that would display the results with no success, could this be the right way of doing it and I just did it wrong?
*Edit*
I’m trying the solution of sanchothefat. Does this look right? This is my whole div for my search results and search query.
<div id="photo-search">
<h2>Search Photos:</h2>
<form action="<?php the_permalink(); ?>" id="searchform" method="get">
<div>
<label for="s" class="screen-reader-text">Search for:</label>
<input type="text" id="search" name="search" value="" />
<input type="hidden" name="post_type" value="photo_group" />
<input type="submit" value="Search" id="searchsubmit" />
</div>
</form>
<?php if( isset( $_REQUEST['search'] ) ) {
query_posts( array(
's' => $_REQUEST['search'],
'post_type' => $_REQUEST['photo_group'],
'paged' => $paged
));
if( have_posts() ) : while ( have_posts() ) :
the_title();
the_content();
endwhile; endif;
wp_reset_query();
}
?>
</div>
I get 404 error page not found when running through the search.
The simplest option if you want to show search results within a page context you’ll need to do a custom loop, otherwise you won’t be able to access the page information.
Change the input with the name
s
to something else likesearch
orq
to stop wordpress from doing it’s usual built in search.Next change the form
action
parameter to the current page’s URL. You can use<?php get_permalink(); ?>
for that.The loop you need to do is as follows:
You can modify the query before it gets processed:
This will get you posts matching the requested post type.
If you want to query multiple post types just pass an array instead:
array('post', 'page', $post_type)
. And to group posts based on the type, check the type within the loop, and store your CPTs inside a temporary array, which you iterate after the normal posts have been displayed.