9 Responses to “Ordering post meta value, numerically”


  • Have you tried this with dates?

  • Hi Johan. Ordering by date should work fine, and you wouldn’t need to do the string => number conversion (i.e. the “+0″ bit). Good luck.

    Simon

  • THANK YOU!! This was perfect. Just like Johan I needed to order several WP_Query loops by date. I just took your code and removed “+0″ from line 9 and it worked like a charm. I was even able to run multiple WP_Query loops inside the filter. The only thing was that if I did not have meta_key=my_variable in the WP_Query arguments then nothing was returned from the loop. That was fine for me though because all of my loops needed the same ordering. Thanks – you are a life saver!

  • Hi Simon, i have tried to use your demo code but it doesn’t show any posts. i simply swapped your fry_views like this:

    function my_posts_orderby( $order_by ) {

    // Order by fry views meta, desc
    $order_by = “price DESC”;
    return $order_by;
    }

    function my_posts_fields( $sql ) {
    $sql .= ‘, wp_postmeta.meta_value+0 AS price ‘;
    return $sql;
    }

    $args = array(
    ‘cat’ => 4,
    ‘showposts’ => 50,
    ‘meta_key’ => ‘price’
    );

    but im gettting nothing have i done something wrong?

  • Thanks!

    This worked perfectly and was very helpful. I ordered things numerically instead of alphabetically. Im using your post template plugin also

    Thanks

  • Hey simon, thanks for the post, was very helpful!

  • Thanks for the code, very helpful. How would you select a category?

Leave a Reply