Support

Account

Home Forums ACF PRO Ordering posts by number field treated like a string

Solved

Ordering posts by number field treated like a string

  • I’m trying to change the order of a custom post type archive by an ACF Number field type but ran into some unexpected results.

    The archive page is using the standard WordPress loop, so are using the pre_get_posts example found on https://www.advancedcustomfields.com/resources/orde-posts-by-custom-fields/ to modify the query.

    It’s working, but seems to be only looking at the first digit of the whole number. Here’s an example, these are the values of the number field of 5 posts.

    4000

    800

    300

    90

    89

    Since I’m ordering these in DESC order, you would assume these posts show up in the order in which I listed them. But here is the order it’s returning.

    90

    89

    800

    4000

    300

    As you can see, it first checks the first digit. Since 90 starts with a 9, it gets put first. If the first number matches, like 800 and 89, it will then order by the second digit. It’s like it’s treating number field value as a string and not an int.

    The only way I have been able to work around this issue is by making sure all numbers have the same amount digits and using 0’s to fill in.

    So if I use the following, it will order correctly.

    4000

    0800

    0300

    0090

    0089

    But this is not an acceptable work around for my situation.

    So as I mentioned, this behavior is telling me that the value from the number field is being treated like a string. So is there a way make this field save the number as an int type?

    Thanks,

    Ryan

  • Oops, I figured out that I had made a mistake.

    In my pre_get_post function I had $query->set('orderby', 'meta_value'); when it should have been $query->set('orderby', 'meta_value_num');

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Ordering posts by number field treated like a string’ is closed to new replies.