Grow your CSS skills. Land your dream job.

Last updated on:

Natural Sort Using Post meta_key

@@ -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.

Comments

  1. ConCy
    Permalink to comment#

    May wanna take a look at this:

    http://digwp.com/2009/09/look-ma-editable-text-regions/

    Check out how too-long code is handles there.
    On hover it expands :)

  2. Dan
    Permalink to comment#

    Update: meta_sort_num has been committed to trunk http://core.trac.wordpress.org/changeset/13501

    Soon won’t need this hack :)

  3. yash
    Permalink to comment#

    how to add “sort post terms” in search or archive pages ?

    for example http://goo.gl/K9sXz

    more example : http://goo.gl/SjYjs

    Most Commented | Most Recent or Alphabetical

    how to do this ? please help me

    thanks in advance :)

  4. Naveed Abbas
    Permalink to comment#

    Thanks
    this code really help me in order to solve my problem.

Leave a Comment

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".