Ordering WordPress Posts By Any Order May06

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: PHP $arr = array(); // First loop through all posts and create an array of the post_id (key) to meta_value_num (value) $args = array('nopaging' => true); $query = new WP_Query($args); if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); $exp_date = get_post_meta(get_the_ID(), 'the_meta_value', true); // If the meta_value is null or 0, make it huge so we can order accordingly if($exp_date == "" || $exp_date == "0") $exp_date = "999999999999"; $arr[get_the_ID()] = $exp_date; endwhile; endif; wp_reset_postdata(); // Sort the array in ascending order asort($arr); $args_posts_in...