I have a problem with search queries. Anytime you put additional queries, like:
mywebsite.com/?s=wordpress&post_type=page
mywebsite.com/?s=wordpress&post_type=page,post
mywebsite.net/?s=wordpress&cat=1
mywebsite.net/?s=wordpress&post_type=post&tag=genesis-post
mywebsite.net/?s=wordpress&post_type=post&tag=thesis-post
it should do a search in the specific scope (post type, category, tag).
In my case, it doesn’t seem to work no matter what I put as an additional parameter, it will display all results containing the word I’m searching for.
In my post types, I have query_var
set to true
so in theory, it should work.
My search.php loop looks like this
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div class="post">
<?php if ( 'post' == get_post_type() ) : ?>
<p class="category"><?php the_category(' '); ?></p>
<?php else : ?>
<p class="category">Resource</p>
<?php endif; ?>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
</div><!-- /post -->
<?php endwhile; ?>
Using a hidden input in my searchform.php doesn’t work either,
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>" class="search">
<input type="text" class="field" name="s" id="s" />
<input type="submit" class="submit" name="submit" value="Go" />
<input type="hidden" name="post_type" value="myposttype" />
</form>
it still searches normal posts, not only within myposttype CPT.
Any idea why the search queries wouldn’t work? Any help appreciated.
I’ve found that passing
post_type
doesn’t restrict searches to that type, but just adds that type to the array it already searches.What you can do to build complex search queries is hook
pre_get_posts
and do a little query manipulation.For a simple example, first I add my own query var to pass to WordPress’s array of known query vars:
Then set up the form to pass a post type, like:
Then add some code to intercept that query var before the database is queried, and set post type:
For debugging, print out the contents of the query object in your
search.php
template to see how everything is being set, and the actual SQL query WordPress generates to query the database. WordPress uses$wp_query
as the global variable which holds the main query:I haven’t tested this, so it might not work quite like I think it will, but try this: