1

I've been trying to find an answer to this, but I haven't found anyone asking the same question.

I have multiple custom post types, with each having its own archive page and search form. As they all use searchform.php, within that I have added the below to make sure each search form only returns results for its respective post type:

<?php $post_type = get_post_type(); ?>
<input type="hidden" name="post_type" value="<?php echo $post_type ?>" />

This works fine on, for example an ebooks custom post type archive page, until I get a search that returns no results. With no results being on the page, get_post_type() returns nothing, and so the next search will return a blank post_type= query string. As a result, it uses the default 'post' post type and returns posts instead of ebooks. This in effect permanently changes the post type to 'post' until I get to another search that returns no results at which the above repeats.

Is there a simple way I can retain the post type between these searches so the post type doesn't change? I've seen lots of posts about how to filter search results for a custom post type, but no one seems to mention this issue.

1 Answer 1

0

You can use get_query_var() to access the post type that was used for the search, and then add that as a hidden field on the search page.

Untested:

printf( 
    '<input type="hidden" name="post_type" value="%s" />', 
    get_query_var( 'post_type', get_post_type() ) 
);
2
  • This worked perfectly. Thank you! I'd upvote but this was my first post.
    – ajs_app
    Commented Jun 28, 2023 at 2:45
  • You're welcome. 🙇‍♂️
    – Caleb
    Commented Jun 28, 2023 at 4:09

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.