WordPress.org

Ready to get started?Download WordPress

Forums

WP_QUERY ordered by custom field (4 posts)

  1. EddieVerso
    Member
    Posted 1 year ago #

    Hi everyone,

    I'm trying to order post by custom field "YEAR" doing this query:

    new WP_Query('cat=5&showposts=-1&meta_key=year&orderby=meta_value&order=ASC');

    unfortunately the order is incorrect. The field is a number field and there are values like 100, 500, 1050.. and so on.

    The output is a little bit uncorrect, like:

    1050 - 100 - 200 - 900 - 400

    I just don't know what could be the problem, so please help me :)

  2. Andrew Bartel
    Member
    Posted 1 year ago #

    Use meta_value_num instead of meta_value on your order by parameter for numeric values.

    https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

  3. EddieVerso
    Member
    Posted 1 year ago #

    oo tnx! Works fine!

    So i suppose that ordering by meta_value will sort the number "alfabetically" (not sure is an english word!)

    Thank you again man!!

  4. Andrew Bartel
    Member
    Posted 1 year ago #

    Yes, exactly. FWIW it's alphabetically.

    Please mark as resolved and happy coding!

Topic Closed

This topic has been closed to new replies.

About this Topic