Support » Themes and Templates » “order by” in a query_posts() ?

  • I want to have one category of my blog come up in an order specified by a timestamp in a post_meta field. I’m already using “cat=$category” in query_posts() to slice and dice the categories I’m showing. Does query_posts() have the ability to add an “order by”? Or can you suggest any other way to do that?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Hi ratbastid – sounds like you want to take a look at the doc at this link:

    Alphebetizing Posts

    Hope this helps,


    Okay, but that sorts on the title field of the wp_posts table. I want to sort on a post meta field.

    Is it kosher to add a field to wp_posts to hold the data I want to sort on? I can use $wpdb to manage that data, no problem. There’s nothing in the codebase that relies on field order out of the database, is there?

    Actually, it appears that even adding my own field doesn’t get it.

    I can add “orderby=title” to the query_posts and it happily alphabetizes, but there’s no database field called “title”. There’s one called “post_title”, though. I presume that there’s a list of keywords for the orderby argument embedded in the codebase somewhere, and that adding my own field is impossible.

    Certainly I haven’t hit on the variation of my new field (“post_promotetime”) that makes the ordering sensitive to it. “orderby=promotetime” doesn’t do it, and neither does “orderby=post_promotetime”. Don’t know what else I’d try…

    What you’re attempting probably can’t be done using query_posts(), as there’s no mechanism at present I’m aware of that lets you pass it JOIN clauses and the like (which would be necessary to tie the postmeta table into the posts query).

    That doesn’t mean there’s no way to do it, however.

    One tack is to code a custom query that collects the posts you want, then use the older posts loop methodology (i.e. foreach($posts as $post) etc.). The downside is it lacks a certain elegance (for what that’s worth), but also can cause issues with other plugins and internal WP elements that rely on the standard loop to be in place.

    Another (and to my mind, better) method is to create a plugin that makes use of the API hooks WordPress offers to *superimpose* your query elements on the default one. An example that’s *close* to what you’re asking for is my Custom Home plugin:

    What’s lacking is the orderby, and of course limiting to a specific category query rather than home page. If you’re interested, a mod of the plugin would be quick and painless for me to code up.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘“order by” in a query_posts() ?’ is closed to new replies.