SUBSCRIBE VIA RSS


Subscribe to our feed

Symfony Experts

Symfony Experts
If you have an urgent question for a symfony-related issue, this is the place to ask.

Topics

Stack Overflow


The old fashioned way

RECENT TUNES

February 26, 2011 – 8:03pm WordPress 3.1 sortable admin tables

With the release of 3.1, WordPress enabled list-type admin screen enhancements to provide sortable columns for list-type screens and better pagination.

This begs the question, how do we make our custom columns sortable, too? If we add custom meta attributes to posts or create custom post types, sometimes it’s nice to display these fields in the admin tables. There are plenty of posts out there that describe how do that. So, let’s focus on how to make these columns sortable.

A new filter was introduced called manage_{$screen->id}_sortable_columns. This works just like the existing filter that we use to add our own column headings to the table. Let’s imagine we created a meta field for our posts called ‘my_author’. (Remember, it’s a good idea to prepend your meta columns with a custom prefix. As an example we’ll use “my_” but you should probably use something more specific in your code. We usually use “stereo_”.


      // add this code to wherever you define your custom post type, usually within a plugin or your theme's functions.php file.
      // you should be familiar with this filter from earlier versions of wp...
      add_filter("manage_edit-".$post_type."_columns", 'my_edit_columns'));
      // this is the new filter which expects an array in the format of id => data
      add_filter("manage_edit-".$post_type."_sortable_columns", 'my_sortable_columns');

      // ...
        function my_sortable_columns($columns)
  	{
  	  $custom = array(
            // meta column id => sortby value used in query
  	    'my_author'    => 'my_author',
  	  );
  	  
  	  return wp_parse_args($custom, $columns);
  	}

If you have it set up correctly, when you view your list of posts in the admin area, the columns defined in your my_sortable_columns function should be active links, and clicking on them toggle sort order.

Posted by in  Web Development   |  

4 Responses to WordPress 3.1 sortable admin tables

  1. Any pointers to the right filter to hook into for sorting the Users page by a user meta value? Thanks.

  2. Paul says:

    Brilliant!!!

    I was struggling to follow a very long winded post that had 10 times as much code as you have here without much success!!!…. Your code worked a treat…. first time!

    Thanks very much for posting this!!

    :-p

  3. Scott Meves says:

    Thanks Paul! -Scott

  4. Pingback: Limitations on Sortable Columns | Ipstenu on Tech

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>