Skip to content

Commit

Permalink
Provide consistent order by adding secondary id sort
Browse files Browse the repository at this point in the history
  • Loading branch information
gwwar committed Apr 13, 2021
1 parent 9e06e59 commit 93da3b9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1064,6 +1064,14 @@ protected function prepare_items_query( $prepared_args = array(), $request = nul
}
}

// If ID is not set, try stabilizing the order. A client can see unexpected ordering when
// items are technically equal to one another (say all pages have a menu_order of 0), but would like to
// see a stable sort. This can especially help for pagination cases.
// See https://core.trac.wordpress.org/ticket/46294 and https://core.trac.wordpress.org/ticket/44349
if ( ! in_array( 'ID', $new_arg, true ) ) {
$new_arg[] = 'ID';
}

// WP_Query expects a space separated list.
$query_args['orderby'] = join( ' ', $new_arg );
} else {
Expand All @@ -1082,7 +1090,17 @@ protected function prepare_items_query( $prepared_args = array(), $request = nul

// WP_Query expects an array with orderby (database table column) keys and order ("asc", "desc") values.
$query_args['orderby'] = $new_arg;

// If ID is not set, try stabilizing the order. A client can see unexpected ordering when
// items are technically equal to one another (say all pages have a menu_order of 0), but would like to
// see a stable sort. This can especially help for pagination cases.
// See https://core.trac.wordpress.org/ticket/46294 and https://core.trac.wordpress.org/ticket/44349
if ( ! isset( $new_arg['ID'] ) ) {
$new_arg['ID'] = 'desc';
}
}

error_log( print_r( $new_arg, true ) );
}

return $query_args;
Expand Down
4 changes: 2 additions & 2 deletions tests/phpunit/tests/rest-api/rest-pages-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -419,12 +419,12 @@ public function test_get_items_multiple_orderby_and_order_query() {
$request->set_param(
'orderby',
array(
'id' => 'desc',
'id' => 'asc',
)
); //eg WP_Query uses ID internally
$response = rest_get_server()->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( array( $id5, $id4, $id3, $id1, $id2 ), wp_list_pluck( $data, 'id' ) );
$this->assertEquals( array( $id2, $id1, $id3, $id4, $id5 ), wp_list_pluck( $data, 'id' ) );

// Invalid 'orderby' should error when in array.
$request = new WP_REST_Request( 'GET', '/wp/v2/pages' );
Expand Down

0 comments on commit 93da3b9

Please sign in to comment.