Sort Posts With The Help Of Custom Fields

WordPress-Christmas-17Quite often, a WordPress developer likes to have posts sorted according to a custom field. If you would write a SQL-statement, it would be quite complex, since you need to JOIN two database tables (wp_posts und wp_postmeta).

But there is a much easier way, if you use the template tags provided by WordPress – in our case we use the function query_posts. Below you can see an example, which includes a custom field in the query, and also sort the posts with the help of this custom field. A short, easy to understand code with effective result:

Bildschirmfoto 2009-12-04 um 21.49.05

query_posts('meta_key=my_day&meta_compare=<=&meta_value=20&orderby=meta_value&order=DESC');

Guest Post

This post is written by Sergej Müller wpseo.org and is a post in our Advent Calendar on WP Engineer about WordPress.
Thank you very much from my part to Sergej.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


Posted

in

by

Comments

9 responses to “Sort Posts With The Help Of Custom Fields”

  1. Dion Hulse (dd32) Avatar

    Please Note: This methodology completely breaks with Pagination of posts. and also increases SQL usage as WordPress is forced to double-query posts.

  2. Sergej Müller Avatar

    @Dion
    This is not an unusual query, the core team recommends this also:
    http://codex.wordpress.org/Template_Tags/query_posts#Order_Parameters

  3. sebastien Avatar
    sebastien

    what’s the result if 2 posts have a same meta_value ?

  4. Sergej Müller Avatar

    @seb
    Then both should be considered by the query.

  5. Matt B Avatar

    Personally, this is not too difficult a concept. I have done more than once, but it is always good as a tip for reference!

  6. maurizio Avatar

    my 2 cents:
    the meta_value field is a text field so the order is alphabetic and not numeric.

    in my experience i need to digit “01”, “02”, “03”…. “10” , “11” to fix the right order.

    with regard to pagination we could add the pagination parameters…
    see here: http://codex.wordpress.org/Template_Tags/query_posts#Pagination_Parameters

  7. ver Avatar
    ver

    what if you have two meta_compare { samle: if i want to query from price 100 price less 600 }

  8. aleSub Avatar

    your method is very very useful, but here’s a hard one:

    what if I need to have the posts sorted by one custom field, but ordered by another?

    I’m trying to figure that out, if I come to something useful I’ll be letting you guys know.

    great site btw!!