• Resolved amp343

    (@amp343)


    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?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter amp343

    (@amp343)

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

    Thread Starter amp343

    (@amp343)

    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:

    https://www.ads-software.com/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.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sort by custom field not working’ is closed to new replies.