Ordering WordPress Posts By Any Order May06

Tags

This Post Was Wrote at

Related Posts

Share This

Ordering WordPress Posts By Any Order

WordPress has a lot of really clever ways to order posts, which can be used to order in almost any way. However, during a recent project I needed to order posts based on one of their meta values, but those meta values needed conditional if statements in to denote what values they should take.

The scenario was such that I needed to order posts based on a numeric value in their meta values, ascending in number, but if that meta value did not exist, or was 0, to be placed last.

So I wanted an order along the lines of:

2, 25, 39, 48, 0, null, null

At first this seemed impossible, and I was left head scratching on how to carry out the order while still including core WordPress mechanisms such as paging. WordPress, by default, doesn’t include an orderby clause where you can just set post ID’s (ie order => (8,99,102,45,22) ). But then I remembered that since version 3.5 WordPress added this clause:

  • post__in‘ – Preserve post ID order given in the post__in array (available with Version 3.5).

I then realised, that if I created an array in the right order, and then passed that to the post__in array I could achieve my desired result. Final code is below: