I added a custom column to wordpress admin post table but I'm not able to get it sortable, button is working but actually nothing happens.
add_filter( 'manage_edit-post_columns', 'new_column');
function new_column( $columns ) {
$column_meta = array( 'meta' => 'Views' );
$columns = array_slice( $columns, 0, 5, true ) $column_meta array_slice( $columns, 2, NULL, true );
return $columns;
}
add_action( 'manage_posts_custom_column' , 'custom_columns' );
function custom_columns( $column ) {
global $post;
switch ( $column ) {
case 'meta':
$metaData = get_post_meta( $post->ID, 'penci_post_views_count', true );
echo $metaData;
break;
}
}
add_filter( 'manage_edit-post_sortable_columns', 'register_sortable_columns' );
// Register the column as sortable
function register_sortable_columns( $columns ) {
$columns['meta'] = 'Views';
return $columns;
}
CodePudding user response:
You're almost there. However, since the post view count is numeric (I'm assuming), you'll need to add a filter to the request to define that it is to be evaluated as such. Add this filter, and you should be good with what you have already.
I also recommend renaming your field from meta
to views
so as not to confuse the issue if someone else looks at this code, or using a core word like meta.
add_filter( 'manage_edit-post_columns', 'new_column' );
function new_column( $columns ) {
$column_meta = array( 'views' => 'Views' );
$columns = array_slice( $columns, 0, 5, true ) $column_meta array_slice( $columns, 2, NULL, true );
return $columns;
}
add_action( 'manage_posts_custom_column', 'custom_columns' );
function custom_columns( $column ) {
global $post;
switch ( $column ) {
case 'views':
$metaData = get_post_meta( $post->ID, 'penci_post_views_count', true );
echo $metaData;
break;
}
}
add_filter( 'manage_edit-post_sortable_columns', 'register_sortable_columns' );
// Register the column as sortable
function register_sortable_columns( $columns ) {
$columns['views'] = 'views';
return $columns;
}
add_filter( 'request', 'views_columns_orderby' );
// Filter the request to evaluate the meta as a number.
function views_columns_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'views' === $vars['orderby'] ) {
$vars = array_merge( $vars,
array(
'meta_key' => 'penci_post_views_count',
'orderby' => 'meta_value_num',
)
);
}
return $vars;
}