1

I am able to filter tags archives by adding a parameter like ?post_type=slug to the url and this works fine except for search results. I mean where the url contains a search term like:

site.com/?s=searched&post_type=slug

How can i make the "&post_type=slug" also work in this case?

EDIT: It wasn't working on my end due to custom function.php code.

  • It should work out of the box, are you doing a custom query inside search.php? – Tom J Nowell Apr 17 '18 at 15:15
  • I'm not, are you sure? I know it seems like it should but doesn't for me. – Michael Rogers Apr 17 '18 at 15:30
  • Are you sure you're not doing something like calling query_posts or WP_Query on your search page? – Tom J Nowell Apr 17 '18 at 16:00
  • 1
    E.g. tomjn.com/?s=talk&post_type=tomjn_talks vs tomjn.com/?s=talk it works on my site, what you're doing should be working. Something else is the problem – Tom J Nowell Apr 17 '18 at 16:01
  • 1
    I undeleted it and edited the title a bit. I have no right to make the answer if you do it i'll accept it. – Michael Rogers Apr 17 '18 at 16:53
2

By all rights it should work, here's the same thing applied to my own site:

tomjn.com/?s=talk&post_type=tomjn_talks vs tomjn.com/?s=talk . Something else is the problem

Specifically, if you replace the main query with a query_posts call or a WP_Query, that query won't take into account parameters passed via the URL unless explicitly passed through manually.

Instead, use the pre_get_posts filter to modify the main query, rather than creating a new query to replace it.This ensures any additional queries passed via the URL will also work, and reduces time spent querying the database significantly for a nice performance boost.

Additionally, if you already use pre_get_posts, setting the post_type will override the URL parameter, so you need to check for its existence

0

The s=keyword url parameter is by default used to search posts that contain that keyword.

To customise this such as the post_type, you need to either:

  1. build a custom search page, you can also see this answer. This question also has some good examples.
  2. Use a plugin
  • sure, have a look at the 2nd answer in this question, there is an example of an html form where you could add an extra <select> dropdown field. This form you need to display either in your sidebar, or header, or search page. – Aurovrata Apr 17 '18 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.