diff --git a/src/wp-includes/user.php b/src/wp-includes/user.php index 5f98b1e478..46088fef04 100644 --- a/src/wp-includes/user.php +++ b/src/wp-includes/user.php @@ -500,6 +500,7 @@ class WP_User_Query { * Prepare the query variables. * * @since 3.1.0 + * @since 4.2.0 Added 'meta_value_num' support for `$orderby` parameter. * @access public * * @param string|array $query { @@ -521,8 +522,9 @@ class WP_User_Query { * @type array $search_columns Array of column names to be searched. Accepts 'ID', 'login', * 'nicename', 'email', 'url'. Default empty array. * @type string $orderby Field to sort the retrieved users by. Accepts 'ID', 'display_name', - * 'login', 'nicename', 'email', 'url', 'registered', 'post_count', or - * 'meta_value'. To use 'meta_value', `$meta_key` must be also be defined. + * 'login', 'nicename', 'email', 'url', 'registered', 'post_count', + * 'meta_value' or 'meta_value_num'. To use 'meta_value' or + * 'meta_value_num', `$meta_key` must be also be defined. * Default 'user_login'. * @type string $order Designates ascending or descending order of users. Accepts 'ASC', * 'DESC'. Default 'ASC'. @@ -631,6 +633,8 @@ class WP_User_Query { $orderby = 'ID'; } elseif ( 'meta_value' == $qv['orderby'] ) { $orderby = "$wpdb->usermeta.meta_value"; + } elseif ( 'meta_value_num' == $qv['orderby'] ) { + $orderby = "$wpdb->usermeta.meta_value+0"; } elseif ( 'include' === $qv['orderby'] && ! empty( $include ) ) { // Sanitized earlier. $include_sql = implode( ',', $include ); diff --git a/tests/phpunit/tests/user/query.php b/tests/phpunit/tests/user/query.php index 4ed7319e6a..37b8d6759a 100644 --- a/tests/phpunit/tests/user/query.php +++ b/tests/phpunit/tests/user/query.php @@ -134,6 +134,30 @@ class Tests_User_Query extends WP_UnitTestCase { $this->assertEquals( $expected, $q->get_results() ); } + /** + * @ticket 27887 + */ + public function test_orderby_meta_value_num() { + $users = $this->factory->user->create_many( 3, array( + 'role' => 'author' + ) ); + + update_user_meta( $users[0], 'user_age', '101' ); + update_user_meta( $users[1], 'user_age', '20' ); + update_user_meta( $users[2], 'user_age', '25' ); + + $q = new WP_User_Query( array( + 'include' => $users, + 'meta_key' => 'user_age', + 'orderby' => 'meta_value_num', + 'fields' => 'ids' + ) ); + + $expected = array( $users[1], $users[2], $users[0] ); + + $this->assertEquals( $expected, $q->get_results() ); + } + /** * @ticket 30064 */