Nov 14, 2011

Wordpress Multiple Category Search

Since when I started wordpress, I had a question in my mind, why wordpress doesn’t give multiple search option? I googled a lot, but couldn’t find a plugin or code which exactly works.

So finally decided to go more into deep of wordpress and php, and came up with a code which works.

Functioning of this code:  Searches all posts using a custom search box where 2 drop-down box will be displayed with values of categories in it.

Have you ever played with search URL? Or tags URL or Categories URL?

Very few might have knowledge that wordpress supports multiple tags or multiple categories. Don’t believe me, in your URL, type this

http://yourblog.com/tag/tag1+tag2

Or

http://yourblog.com/tag/tag1,tag2

Now what does this means? Simple when you type tag1+tag2 it will show you posts with having both the tags. And when you type tag1, tag2 it will show you all the posts having either tag in it.

Same works for categories.

http://yourblog.com/category/cat1+cat2
http://yourblog.com/category/cat1,cat2

Now I tried this same functionality in search URL of Wordpress.

http://yourblog.com/?s=html&cat=114

And woila it worked!!!!

Here “s” is your search term and “cat=114” is your category ID. This will work and display all the posts with the search term only in category ID 114.

But the only problem in this is that it will just take one category at a time.

Wordpress doesn’t supports this URL

http://yourblog.com/?s=html&cat=114+115

Here comes a big problem. After a lot of search I found that “+” is considered as a space in URL. So we need to write a function which will make this space act as a + operator.



[php]
add_action( 'parse_request', 'category_search_logic', 11 );
function category_search_logic( $query ) {
if ( ! isset( $query->query_vars[ 'cat' ] ) )
return $query;
// split cat query on a space to get IDs separated by '+' in URL
$cats = explode( ' ', $query->query_vars[ 'cat' ] );
if ( count( $cats ) > 1 ) {
unset( $query->query_vars[ 'cat' ] );
$query->query_vars[ 'category__and' ] = $cats;
}
return $query;
}

function check()
{
$url = $_SERVER["REQUEST_URI"];
$query = str_replace('&cats=', '+', $url);
if(isset($query) && ($query != $url))
{
header('Location:'.$query);
}
}

add_action('parse_query', 'check');
[/php]

After getting this function in our functions.php file, the multiple categories URL with search will work.

So it’s time to design a simple search form.

Paste this anywhere in your theme.



[html]
<!-- Search Form -->
<div style="margin:10px 0 10px 0;">
<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<table cellspacing="5">
<tr>
<td>
<label for="s" style="margin:10px;">Search</label>
</td>

<td>
<input type="text" class="field" name="s" style="width: 100px;"/>
</td>
<td>
<?php wp_dropdown_categories('show_count=1&hierarchical=1'); ?>
</td>
<td>
<?php wp_dropdown_categories('show_count=1&hierarchical=1&name=cats'); ?>
</td>
<td>
<input type="submit" class="submit" name="submit" id="searchsubmit" value="Search" style="display: block; position: relative; top: 7px;"/>
</td>
</tr>
</table>
</form>
</div>
<!-- Search Form -->


[/html]

That’s it, now just go and try your wordpress site will be having a multiple category search option. No plugin and no hundred lines of code, and best part, it’s fully flexible to use. If you want one more category drop down then just copy paste the category php code one more time.




27 comments :

  1. Hi ntechi! I was very happy to read your tutorial, as I was facing this issue in the last couple of days! I tried your solution, but did not actually work for me. The search seems to be looking only in the posts of the category selected in the second drop-down menu and totally ignore the selection made in the first drop-down menu. Do you have any suggestion on that?

    ReplyDelete
  2. @31a20c99eeb33ed7f9f1c05a177537fd:disqus  Can you share your websites link and did you pasted the function code in functions.php file?

    ReplyDelete
  3. Hi! I did paste the function code. You can take a look at http://www.soulme.gr/directory-soulme/, I hope you won't need to figure out what is written, it is in Greek :-)

    ReplyDelete
  4. Hello, I also have a problem! The plugin didnt work good for me, cuz I always have to press on "Reset", so I checked he google and got your web. I got the same problem as kelly. And yes, i posted the code to function.php. The web is http://ecc.lv , can you write me a solution to info@lussvision.com . Thank you very much.

    ReplyDelete
  5. @31a20c99eeb33ed7f9f1c05a177537fd:disqus & @92abb6ffadb794d3aafdf1365a808a5a:disqus   Thanks for your update, I have fixed that problem, now just copy and paste the above codes again, now it should work for you fine.

    ReplyDelete
  6. Pretty sad, but still it doesn't work for me. Maybe the problem is that i use %postname% for permalink, because I get a such link after search /category/akciju-slaideris/?s+37&submit=Search . Hope it's not, because I need such link form for SEO. I'm almost done with the web, and the only problem left is Search. Hope I can fix it with your help. I cut the code for FIELD, because I need only search by categories. Is that possible e.g. in first category line I got only one Parent category with sub-categories list and in the second one another one Parent category with sub-categories list. Thank you for your quick answers!

    ReplyDelete
  7. @92abb6ffadb794d3aafdf1365a808a5a:disqus  In that case you need to modify the code, you said you are not using search box, so you ll need to remove some code, I ll update you soon with your code.

    ReplyDelete
  8. I'm using Wordpresss 3.2.1 Version, Maybe I should update it?

    ReplyDelete
  9. Anysolution for this? :( Still shows  one category in  two fields.

    ReplyDelete
  10. Thank you so much! I just tested your new code and it takes into account both categories now :-)
    I see in your demo that it works fine even if one does not define any search terms, using the code above though I do not get the same behavior.
    Is there something else to be done?

    Thanks again for your great help!!!

    ReplyDelete
  11. Great its working now, I am still into coding for getting it fully worked. But yes it is possible. I ll update you once it functions fully, actually short on time, if any one can get this working then please feel free for sharing it.

    ReplyDelete
  12. I will surely keep you posted on any developments from my side! Thanks again for your great support!!!

    ReplyDelete
  13. Hi,

    Just starting to explore this functionality.  Curious if it has been tested using Custom Post Type and Custom Taxonomies.

    ReplyDelete
  14. NO idea @7512772fd9dbc23edefbe5e8132d0983:disqus for custom post type and for taxonomies, if you get a success then please feel free to share here.

    ReplyDelete
  15. remove the contents from htaccess file, and let the wordpress generate new content, just check and see.

    ReplyDelete
  16. Hi, this is a feature that would be great on my site.

    I have added the code to the functions.php and added the searchform in a post.

    The search feature appears but the drop down menus do not.

    any help would be good.

    ReplyDelete
  17. I got it working, now just need to get it so dropdown list 1 shows certain cats

    and drop down 2 another set of cats ???

    ReplyDelete
  18. 'orderby=id&use_desc_for_title=0&child_of=*****'

    where **** is eneter your parent ID

    ReplyDelete
  19. I now have the problem of the search only searching the one cat ??? any solutions

    ReplyDelete
  20. Can you describe it?

    ReplyDelete
  21. You have two drop down menus.


    When you search it will only search the last drop down menu that appears in the coding.

    I am unsure why it wont search both.

    ReplyDelete
  22. Your plugin returns a internal server error???

    ReplyDelete
  23. @all I know theirs some problem with the code cause wordpress always changes its core in every update due to which my function keeps lagging.

    Currently I am more into other projects so.....

    But I ll update this function soon, its still work in progress

    ReplyDelete
  24. Hi, this is almost so great... but I get this error. Any thoughts?


    Internal Server Error

    The server encountered an internal error or
    misconfiguration and was unable to complete
    your request.

    Please contact the server administrator,
    webmaster@semaphorestudios.andreagoldman.org and inform them of the time the error occurred,
    and anything you might have done that may have
    caused the error.

    More information about this error may be available
    in the server error log.

    Additionally, a 500 Internal Server Error
    error was encountered while trying to use an ErrorDocument to handle the request.

    ReplyDelete
  25. check your .htaccess file

    ReplyDelete
  26. Hello, I'm Antonio and I have wordpress 3.42 multisite and buddypress 1.6. Where I paste your code in fuction php?

    ReplyDelete
  27. For me the same message, the error log record say:

    PHP Warning: Cannot modify header information - headers already sent by (output started at .... it refer to 20 line in the function "check"

    ReplyDelete