I'm trying to return only pages in search results.
This is working:
/?s=term&post_type=post
It returns only posts, no pages.
But the opposite is not working:
/?s=term&post_type=page
This is returning pages and posts.
How do I return only pages?
Edit
Forgot to mention, so I'm trying to allow the ability for the user to click two links at the top of the search results page.
<a href="/?s=term&post_type=post">Search Only Posts</a>
<a href="/?s=term&post_type=page">Search Only Pages</a>
So, I can't just globally set all search results to only be one or the other.
I'm trying to return only pages in search results.
This is working:
/?s=term&post_type=post
It returns only posts, no pages.
But the opposite is not working:
/?s=term&post_type=page
This is returning pages and posts.
How do I return only pages?
Edit
Forgot to mention, so I'm trying to allow the ability for the user to click two links at the top of the search results page.
<a href="/?s=term&post_type=post">Search Only Posts</a>
<a href="/?s=term&post_type=page">Search Only Pages</a>
So, I can't just globally set all search results to only be one or the other.
Share Improve this question edited Jul 17, 2016 at 15:35 Corey asked Jul 17, 2016 at 14:58 CoreyCorey 3217 silver badges17 bronze badges 1 |2 Answers
Reset to default 5You can enforce a post type per callback on pre_get_posts
:
is_admin() || add_action( 'pre_get_posts', function( \WP_Query $query ) {
$post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );
if ( $post_type && $query->is_main_query() && $query->is_search() )
$query->set( 'post_type', [ $post_type ] );
});
If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin.
In your search.php, find The Loop and insert this code just after it. You can recognize the Loop because it usually starts with:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();?>
Code to be inserted:
if (is_search() && ($post->post_type=='post')) continue;
So, your code should be like this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();?>
<?php if (is_search() && ($post->post_type=='post')) continue; ?>
Let me know if it worked.
pre_get_posts
is your friend! – Tom J Nowell ♦ Commented Jul 17, 2016 at 15:19