Making post views as sortable

I am using custom field on wordpress admin posts page by adding the following code and then trying to sort the posts based on post views but the sorting does isn’t working. Here is the code I have added in functions.php:

add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

// Register the column as sortable
function posts_column_register_sortable( $columns ) {
$columns['post_views'] = 'post_views';

return $columns;
}
add_filter( 'manage_edit-post_sortable_columns', 'posts_column_register_sortable' );


function posts_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'post_views_count' == $vars['orderby'] ) {
    $vars = array_merge( $vars, array(
        'meta_key' => 'post_views',
        'orderby' => 'meta_value_num'
    ) );
}

return $vars;
}
add_filter( 'request', 'posts_column_orderby' );


function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0";
    }
    return $count;
}
function setPostViews($postID) {
if (!current_user_can('level_7') ) :
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
endif;
}

Now the problem is that I can see the post views in the wordpress admin edit.php page and the volumn Views is also sortable but clicking on Views column doesn’t sort the posts based on views.

Read More

Please help me to solve this problem.

Related posts

Leave a Reply

1 comment

  1. The posts_column_register_sortable function, hooked onto posts_column_register_sortable returns an array with names of sortable columns as keys and their corresponding value what to sort by (e.g. ‘post_title’ etc).

    In your case you’ve given it ‘post_views’ to sort by, which doesn’t exist as a column – so you need to tell WordPress how to sort by it. Which you kind of do in the posts_column_orderby function, hooked onto request. However the variable the orderby variable you check is 'post_views_count', not the ‘post_views’ you set above. Change one of them to match the other and it should work.