• Resolved kim crimson

    (@kim-crimson)


    Hi,

    I’m trying to make an option panel for a site where all the post titles are numbers. But I can’t figure out how to sort them in numeric order. I’m using get_posts like this:

    $rooms = get_posts('category=1&numberposts=200&orderby=title&order=asc');
     	foreach($rooms as $post) :
       	setup_postdata($post);
                  --> content here
            endforeach;

    I’m guessing it’s because the post titles are strings and not numbers. But at the same time I need it to understand letters as well. I could have 6 posts for example and they would have names like:

    1
    5
    12
    27d
    45
    112

    But I just can’t figure out how to sort them correctly. I’ve tried to put sort($rooms); after the get_posts query, but then it outputs the rooms like this:

    1
    5
    45
    12
    112
    27d

    I’ve looked everywhere for the answer but I can’t find it. Hope someone can help me!
    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The easiest way is probably defining your own comparision function and then using usort. Something like:

    function cmp($a, $b) {
        if ($a->post_title== $b->post_title) {
            return 0;
        }
        return ((int)$a->post_title < (int)$b->post_title) ? -1 : 1;
    }

    and then: uasort($rooms, 'cmp');

    could probably work. See: http://www.php.net/manual/en/function.uasort.php for more info, examples, etc.

    Thread Starter kim crimson

    (@kim-crimson)

    Great! That works absolutely perfectly. I had to remove the (int) though, as there are some letters in the post titles too. But thanks so much for your help! really appreciate it.

    You’re welcome, glad I could help!

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘can't sort my get_posts query numerically’ is closed to new replies.