How do I get a custom orderby in WP_Query (not ASC nor DESC)? So, order have to be not alphabetically, nor numerical. It have to be custom.

For example I want to sort by post's meta field thing in next order:

  1. Bag
  2. Car
  3. Apple

So all bags come first, then cars then apples.

  • Please make your question understandable. Be explicit about what you want your order to be Commented Feb 4, 2018 at 8:17
  • You want to order by a meta value? Or something else?
    – swissspidy
    Commented Feb 4, 2018 at 9:00
  • @MarkKaplun updated.
    – Kuraga
    Commented Feb 4, 2018 at 11:55
  • @swissspidy yes (updated)
    – Kuraga
    Commented Feb 4, 2018 at 11:55

1 Answer 1


You probably can find some way to make MySQL do the sort for you, but an alternative approach is to make it into an ASC/DESC order by adding additional meta in which you put a numeric sort order value based on whether it is apple, bag, etc and update it when the post is saved. Than all you need to do is to sort by the "sort" meta field.

  • Thanks! I did have an idea to transform (with SQL) "Apple"/etc. to "2", etc. (during request!)... I think it is the same or do you propose to create a real post's field? P.S. Can we apply an SQL function during creating a meta (in request)?
    – Kuraga
    Commented Feb 4, 2018 at 12:35
  • I assume that you can write a compare function is sql and use it for the sort part of the query by using one of the wp_query filters. Maybe you can even write it as some kind of "stored procedure" but I never gone down this specific rabbit hole. What I suggest here is just easier to understand for most of wordpress developers. The drawback is that you will have harder time if you need to change the order after the DB is alrady populated Commented Feb 4, 2018 at 13:00
  • .... but if you do not need pagination of some sort, the best way is actually to sort the results in PHP. Commented Feb 4, 2018 at 13:02
  • The question now is how to apply "stored procedure" in WP Query without manual SQL :-) Ok, thanks!
    – Kuraga
    Commented Feb 4, 2018 at 14:05
  • stored procedures means "manual" Sql" was just thinking out loud ;) Commented Feb 4, 2018 at 15:40

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.