How To Add Sortable Custom Columns in WordPress Dashboard

In a previous tutorial, I showed you how to display a plain, non-sortable “Views” Column for Posts in the WordPress Dashboard. In this tutorial, I will show you how to make that “Views” Custom Column Sortable for Posts, ascending or descending based on the number of post views.

A WordPress developer asked me the following question: Is there a way to make the “Views” Custom Column sortable in the WordPress dashboard? And the answer is YES and here is how to make a Sortable Custom Column for Posts.

Before: using CODE-3 | WP Dashboard

The picture below show the Non-Sortable Views Column in the WordPress dashboard, when you implement CODE-3 from my previous tutorial.

WordPress dashboard: Non Sorted Views Column for Posts.

After: using CODE-3A | WP Dashboard

The pictures below show the Sortable Views Column in the WordPress dashboard, after implementing CODE-3A discussed later.

WordPress dashboard: Sorting Views Column for Posts in Descending order.

WordPress dashboard: Sorting Views Column for Posts in Ascending order.

Prerequisite

My previous tutorial: How To Track & Display Post Views Count in WordPress Without a Plugin, is the basis for this post. Implementing (CODE-1 and CODE-2) or (CODE-1 and CODE-2a) of my previous tutorial is a MUST!

The difference will be:

  1. If you add CODE-3 from my previous tutorial, you will get a Non-Sorted Custom Views Column.
  2. However, if you add CODE-3A from this tutorial, you will get a Sorted Custom Views Column, descending or ascending by views count. A nice feature that will make the new custom column support sorting.

Enough with talking, show me the Code!

Sortable Post Views Column In WP Dashboard | functions.php

Open the functions.php file located in your theme´s folder, and add (copy and paste) the following CODE-3A. Save the file and upload it to your server.

Then Login to your WordPress dashboard. In your Administration Screens go to the “Posts” tab, and you will notice a new Views column that displays the number of views for each post. What´s nice about it is that you can sort the Views column ascending or descending.

CODE-3A :: Sortable Custom Views Column for Posts in WP dashboard

Note: To scroll within the code: You can also click on the code window and use your keyboard´s arrow keys.

<?php
/********************************* CODE-3A ***************************************
* @Author: Boutros AbiChedid 
* @Date:   February 7, 2012
* @Websites: bacsoftwareconsulting.com/ ; blueoliveonline.com/
* @Description: Adds a Sortable 'Views' Columnn to the Posts Tab in WP dashboard.
* Sortable: Ascending or Descending based on the number of views count.
* This code requires CODE-1 and CODE-2 (or CODE-2a) from my previous tutorial.
* @Tested on: WordPress version 3.2.1
*********************************************************************************/ 

//Function: Gets the number of Post Views to be used later.
function get_PostViews($post_ID){
    $count_key = 'post_views_count';
    //Returns values of the custom field with the specified key from the specified post.
	$count = get_post_meta($post_ID, $count_key, true);

	return $count;
}
//Function: Add/Register the Non-sortable 'Views' Column to your Posts tab in WP Dashboard.
function post_column_views($newcolumn){
	//Retrieves the translated string, if translation exists, and assign it to the 'default' array.
    $newcolumn['post_views'] = __('Views');
    return $newcolumn;
}
//Hooks a function to a specific filter action.
//Applied to the list of columns to print on the manage posts screen.
add_filter( 'manage_posts_columns', 'post_column_views' );

//Function: Populate the 'Views' Column with the views count in the WP dashboard.
function post_custom_column_views($column_name, $id){	
	if($column_name === 'post_views'){
		// Display the Post View Count of the current post.
		// get_the_ID() - Returns the numeric ID of the current post.
        echo get_PostViews(get_the_ID());
    }
}
//Hooks a function to a specific action. 
//allows you to add custom columns to the list post/custom post type pages.
//'10' default: specify the function's priority.
//'2' is the number of the functions' arguments.
add_action('manage_posts_custom_column', 'post_custom_column_views',10,2);

/**UP TO HERE IS THE SAME AS CODE-3. NEXT IS WHAT IS REQUIRED FOR SORTABLE 'VIEWS' COLUMN**/

//Function: Register the 'Views' column as sortable in the WP dashboard.
function register_post_column_views_sortable( $newcolumn ) {
	$newcolumn['post_views'] = 'post_views';
	return $newcolumn;
}
add_filter( 'manage_edit-post_sortable_columns', 'register_post_column_views_sortable' );

//Function: Sort Post Views in WP dashboard based on the Number of Views (ASC or DESC).
function sort_views_column( $vars ) 
{
	if ( isset( $vars['orderby'] ) && 'post_views' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'post_views_count', //Custom field key
			'orderby' => 'meta_value_num') //Custom field value (number)
		);
	}
	return $vars;
}
add_filter( 'request', 'sort_views_column' );
?>

CODE-3A Notes:

Some themes have more variations of the functions.php file, so look at their documentation and see where best to add the code.

CODE-3A requires (CODE-1 AND CODE-2) or (CODE-1 AND CODE-2a) of my previous tutorial.

If you added CODE-3A to your functions.php file, and you still don´t see the Views Column in your Dashboard, then make sure that your screen options is set to display the new column as shown in the image below:

WordPress dashboard: Screen options for Posts.

The difference between CODE-3A and CODE-3 are lines 46 to 64 of the code.

CODE-3A works on WordPress 3.1 and higher (sortable custom columns in WordPress dashboard is a 3.1+ feature). But I hope that you will upgrade to the latest version.

If you want to remove the “Views” Column from the WordPress Dashboard, then you have 2 choices:

  1. Either delete CODE-3A from your theme´s functions.php file.
  2. Or Keep CODE-3A, but add the following function to the end of CODE-3A.
/**Function: Remove the 'Views' Column from your Posts Tab in WP Dashboard**/
function remove_user_posts_column($column_headers) {
    unset($column_headers['post_views']);
    return $column_headers;
}
add_action('manage_posts_columns','remove_user_posts_column');

General Warning

When you add several PHP code blocks in your theme´s funtions.php file, make sure that you do NOT leave any white space (spaces, newline) before the opening PHP tag (<?php) or after the closing PHP tag (?>). The correct way is as follows:

<?php 
//Some Code here beetween the opening PHP tag (above) 
//and the closing PHP tag (below)...
?>
<?php 
//Some other Code here ...
?>

In the above code, if you leave any white space or a newline between lines 4 and 5, you will get the following error: “Warning: Cannot modify header information - headers already sent by…

Your Turn to Talk

You now have the choice to show the Post Views Custom Column in your WordPress Dashboard in a Sortable format, and without a plugin. In the dashboard, the code adds a new Sortable Custom Column for Posts that tracks the number of views of your Posts.

How easy did you find this tutorial to implement? Do you have something to add or anything else to say? If so, please share your opinion in the comments section. Your opinion matters, unless it is a Spam.

References

If you found this post useful, please consider: linking back to it, subscribing by email to future posts, or subscribing to the RSS feed to have new articles delivered to your feed reader, or feel free to donate. Thanks!

About the Author |
Boutros is a professional Drupal & WordPress developer, Web developer, Web designer, Software Engineer and Blogger. He strives for pixel perfect design, clean robust code, and user-friendly interface. If you have a project in mind and like his work, feel free to contact him. Connect with Boutros on Twitter, and LinkedIn.
Visit Boutros AbiChedid Website.

15 Responses to “How To Add Sortable Custom Columns in WordPress Dashboard”

  1. Jesse Hewitt says:

    Great tutorial, but I am running into a problem. It works great for posts, but seems to break for custom post types so that they are not sortable. Do you know a fix for this?

    • Carol says:

      I’d love to know the answer to this one, too. I did get the views showing on custom post types, using his prior tweak, but cannot get them to sort.

      • Carol says:

        I found it! Below where his code says:

        add_filter( 'manage_edit-post_sortable_columns', 'register_posts_column_views_sortable' );
        

        You want to add a new line for each custom post type, as follows, using the appropriate custom post type slug:

        add_filter( 'manage_edit-CUSTOMPOSTTYPENAME_sortable_columns', 'register_posts_column_views_sortable' );
        

        Alternatively, if you want all this to work for posts, pages, and custom post types, ignore his prior fix for custom post types. Instead, after:

        add_filter('manage_posts_columns', 'posts_column_views');
        add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
        

        add these lines:

        add_filter('manage_pages_columns', 'posts_column_views');
        add_action('manage_pages_custom_column', 'posts_custom_column_views',5,2);
        

        Then, after

        add_filter( 'manage_edit-post_sortable_columns', 'register_posts_column_views_sortable' );
        

        add this line for each custom post type, using the appropriate custom post type slug:

        add_filter( 'manage_edit-CUSTOMPOSTTYPENAME_sortable_columns', 'register_posts_column_views_sortable' );
        

        and this for pages:

        add_filter( 'manage_edit-page_sortable_columns', 'register_posts_column_views_sortable' );
        
  2. Alex says:

    Hi there,
    thanks for your code, first of all..
    I’m having a little problem with the implementation ’cause it seems that in my wp version (3.4.1) there’s no hook for the manage_edit-post_sortable_columns function.. I tried to put a var_dump in there and it didn’t shows up, so I tried to search in the whole wp directory for the hook, but I couldn’t find it..
    Can you guess what might be the problem here?
    thank you

  3. Geetha Rai says:

    I have tried this in my new WP project but it doesn’t shows the views, I have other some functions in function.php, does it clash with above code? any advise will be thankful.

  4. Alan says:

    your code was indeed correct, and the problem i mentioned in your other post got resolved as well with a clean db, thanks for your patience & have a great weekend

  5. Alan says:

    Hmmm… I first tried like originally posted and the posts list was reduced to zero when sorting the Views column, then changed line 48 to what I suggested and it worked.

    • That is very interesting. When you click on the header of the ‘Views’ Column, does it sort them correctly ascending and descending?

      • Alan says:

        the posts list is reduced to zero when sorting the Views column, i.e. no posts at all are displayed/listed, and when i click on another header (title, author, date ) all posts are displayed/listed again.

        and with $newcolumn['post_views'] = ‘Views’;
        they get listed ASC/DESC correctly.

        • Alan says:

          they get listed ASC/DESC correctly.

          i added more posts and did some further testing
          sometimes the ASC/DESC Views list is correct, sometimes not
          maybe the db has been smoking grass lately, i’ll do fresh wp install

        • Let me know Alan. The code is not theme dependent and we have the same version of WP (3.3.1).

  6. Alan says:

    Hi Boutros,

    FYI, line 48 of CODE-3A must be:

    $newcolumn['post_views'] = ‘Views’;

    • Hi Alan,

      Line 48 of the code is correct as it is.
      Your statement is wrong. With your suggestion the ‘Views’ column in the dashboard will not sort the posts correctly ascending or descending.
      Try it out.
      Boutros.