Home » Make WP Custom Columns Sortable

Next good and useful thing to do after adding a new custom column to the Posts Manage Page of the WordPress Admin Page is to make it sortable.

This is a continuation of the tutorial Add New Columns To WP Posts Manage Page, thus we will be updating the function where the hook manage_posts_columns is added. And will also add a new request filter request


Step 1.

Update the return data of the function new_posts_column(). Make the return value a clickable link and include all needed parameters. This is the clickable column header where the default order is DESC to ASC.

  • Change this
        $columns['views'] = 'Views';
        return $columns;
  • Into this
        $columns['views'] = '<a href="edit.php?post_type=post&orderby=views&order=' . ((get_query_var('meta_key') == 'total_views_count' && get_query_var('order')=='DESC') ? 'asc' : 'desc') . '">Views</a>';
        return $columns;

The complete function will look like below.

function new_posts_column( $columns ) {
    $columns['views']  = '<a href="edit.php?post_type=post&orderby=views&order=' . ((get_query_var('meta_key') == 'total_views_count' && get_query_var('order')=='DESC') ? 'asc' : 'desc') . '">Views</a>';
    return $columns;
add_filter( 'manage_posts_columns', 'new_posts_column' );

Step 2.

Create a new function to add a request filter.

function new_posts_columns_sorting( $vars ) {
    if ( isset( $vars['orderby'] ) && $vars['orderby'] == 'views' ) {       
        $vars = array_merge( $vars, array (
            'meta_key'  => 'total_views_count',
            'orderby'   => 'meta_value_num',
        ) );

    return $vars;
add_filter( 'request', 'new_posts_columns_sorting' );








Leave a Reply

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