wordpress Natural Sort Using Post meta_key

by in , 0

@@ -2033,6 +2033,7 @@

      if ( !empty($q['meta_key']) ) {
              $allowed_keys[] = $q['meta_key'];
              $allowed_keys[] = 'meta_value';
+             $allowed_keys[] = 'meta_value_num';
      }
      $q['orderby'] = urldecode($q['orderby']);
      $q['orderby'] = addslashes_gpc($q['orderby']);

@@ -2056,6 +2057,9 @@

      case 'meta_value':
              $orderby = "$wpdb->postmeta.meta_value";
              break;
+     case 'meta_value_num':
+             $orderby = "$wpdb->postmeta.meta_value+0";
+             break;
      default:
              $orderby = "$wpdb->posts.post_" . $orderby;
}

This is a direct edit to a core file: /wp-includes/query.php Note the plus signs in the above code indicate new lines to add.

Author Notes:

A client wanted me to setup a custom field called "Guide Rank" which allowed them to assign #1 - 20 for a list of Bars they were posting about.

After running the posts query I found that the meta_value was being treated as a string and as such the sort order was jumbled:

eg. 1, 10, 2, 3css-tricks.comC 7 , 8 , 9

To get WordPress/MySQL to use "Natural Sort Order" you just need to apply +0 to the field name and it'll be treated as a number (eg. meta_value+0).

So that existing behavior is not interrupted I've just added the new type 'meta_value_num'.

My query line now looks like:

$guide_posts = new WP_Query("cat=12&meta_key=guide_rank&orderby=meta_value_num&order=ASC&showposts=10");

Which returns: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

This is up for inclusion in the WordPress trunk - so hopefully once it gets applied there should be no need for manually editing the file.

Leave a Reply