Create sortable custom columns / post types in wordpress admin

Its really nice to be able to use wordpress table sorting feature for your custom post types. There has been a lot of post in this this area. The fact is that its actually really simple.

Say I have a custom post type called “lesson”. Now I want to sort the lesson table based on certain meta_key (say _lesson_parent) of the lesson post.

This is the screenshot of my lesson post type.


In functions.php, I need to add the filters and hooks first.

if (is_admin()) {
    add_filter( 'manage_edit-lesson_columns', 'my_custom_lesson_column' );
    add_filter( 'manage_edit-lesson_sortable_columns', 'my_custom_lesson_column_sortable');
    add_action( 'manage_lesson_posts_custom_column', 'my_add_column_data', 11, 2 );

Now we need to create the 3 functions. Read the comments in the code… Its easy.

function my_custom_lesson_column ($col) {
  // I've created 2 columns here. lesson-order is the menu-order of the posts
  $col['lesson-order'] = _x('Lesson Order', 'column name', 'my-plugin' );
  // lesson-parent is the meta_key of the post. I want to be able to sort this column.
  $col['lesson-parent'] = _x( 'Lesson Parent', 'column name', 'my-plugin' );
  return $col;

function my_custom_lesson_column_sortable($col) {
  // Here, I define my sortable column, ie lesson-parent. The meta_key in the post_meta table is called _lesson_parent
  $col['lesson-parent'] = _x( '_lesson_parent', 'column name', 'my-plugin' );
  return $col;

// add data into the 2 columns. I can define whatever I want to be displayed in the columns here.
function my_add_column_data ( $column_name, $id ) {
  switch ( $column_name ) {
    case 'lesson-parent':
      // get the parent lesson title
      $lesson_parent_id = get_post_meta( $id, '_lesson_parent', true);
    case 'lesson-order':
      // get the menu order the the lesson
      echo get_post($id)->menu_order;
Like it.? Share it:

Comments are closed.