Forums

[resolved] Sort by custom field not working (3 posts)

  1. amp343
    Member
    Posted 2 years ago #

    Hey there,

    I'm running into a problem trying to sort my posts by custom fields. I set my custom fields to begin with, then used this query_posts to sort by a particular field:

    query_posts(orderby=meta_value&meta_key=goals&sorder=DESC&posts_per_page=1)

    ... At first, that worked.

    However, when I go back in and change my custom field values, then save the posts, it still sorts in the PREVIOUS order. I know the values are being updated correctly to the database, as the get_post_meta function is reflecting the most current changes. The sort just doesn't seem to acknowledge them.

    Any insight?

  2. amp343
    Member
    Posted 2 years ago #

    Hm, I think this has something to do with my meta values being numerical -- anyone else experience this?

  3. amp343
    Member
    Posted 2 years ago #

    Well, looks like I'm able to answer my own question after researching a bit more:

    When you try to sort by a numeric query using the query_posts() function, PHP interprets it as a string. So, 10 is interpreted as "1", etc... which, you can imagine, throws the sorting all off.

    In order to get around this, I had to use a custom select query rather than the query_posts() function - and also use this fix as part of my query:

    http://wordpress.org/support/topic/286391?replies=12

    Essentially, including this line
    ORDER BY wpostmeta.meta_value+0 DESC
    forces the field to be interpreted as an integer rather than a string - exactly what I was trying to do. Sorting works just as I had intended.

Topic Closed

This topic has been closed to new replies.

About this Topic