19 thoughts on “Ordering post meta value, numerically”

  1. 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

  2. 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!

  3. 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?

  4. Thanks!

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

    Thanks

  5. Wow, this looks like a great method, but it doesn’t seem to work for custom post types. (In my case, ‘event’ by ‘start-date ASC’)

    In any case, the loop isn’t outputting anything, without any errors.

    Any ideas?

  6. I’m new to all this, where do I have to put the code? I’ve tried placing it on the template page but get the following error: Parse error: syntax error, unexpected T_STRING

  7. Andrew: Take a template with a working ‘wordpress loop’ and change only the loop part to either Simon’s demo code or my second paste-bin. Any old template would do. You could take a copy of category.php for instance.

    1. Thanks for replying John James, I appreciate it! Andrew –
      It’s likely that you are running PHP4, which is an old version of
      the server software required to run WordPress. Soon WordPress
      itself will require you to run a more recent version of PHP. If you
      contact your web host they should be very happy to help. Good
      luck!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.