How to prioritize categories in search (WordPress)

As a preface, if anyone has a more elegant solution to this, or found this post helpful please comment below.

While working on a site for a client I came across what at the time seemed like a very simple problem: when user performs a search, posts from a certain category (and its subcategories) should come out on top.

No problem – wp_query, order by and we’re set – however there’s nothing to order by.

  • You can’t order by categories for this particular problem.
  • You can’t order by meta_key or meta_value if other posts don’t have that value. (All posts in the category that I wanted on top had a specific meta_key/value combination).
    That includes injecting into the SQL statement. As a sidenote, while working on this I figured out a way to order by multiple meta_values. Doesn’t help here but good to know.
  • Using multiple loops is a solution that many people on the net used for this particular problem. Though once you start using multiple loops for this, you get into pagination issues with The Loop. Too much headache to deal with. I want a simple solution.

I was about to write a plugin to prioritize posts/categories when I came across a little gem of a plugin that does exactly that. It seems to be doing a simple task but it’s actually quite brilliant if you take a look at the code.

Combined with simply ordering posts by title with wp_query, I now have certain categories on top of search results and all posts are ordered by title.

You can grab this plugin here:

Happy WordPressing.