0

I display a custom table using the WP_List_Table class. Everything works, but I want the default orderby to be numeric (by ID). If it is by string it works.

this is the function:

private function sort_data( $a, $b )
    {
        // Set defaults
        $orderby = 'id';
        $order = 'desc';
        // If orderby is set, use this as the sort column
        if(!empty($_GET['orderby']))
        {
            $orderby = $_GET['orderby'];
        }
        // If order is set use this as the order
        if(!empty($_GET['order']))
        {
            $order = $_GET['order'];
        }
        $result = strcmp( $a[$orderby], $b[$orderby] );
        if($order === 'asc')
        {
            return $result;
        }
        return -$result;
    }

The outcome is as this:

  • 9
  • 8
  • 7
  • 6
  • 5
  • 4
  • 3
  • 2
  • 11
  • 10
3

Try the strnatcmp() for "natural" ordering, instead of strcmp() (src) or handle the ID ordering specially, e.g. with typecasting and the spaceship operator <=> in PHP 7.

  • 1
    Yes, exactly what I was looking for. Thanks a lot! – SjaakvBrabant May 30 '17 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.