我有一个自定义字段,用于存储为数字的视图计数。我添加了一个视图列,并使其可排序,但排序不正确。
单击“视图”列时的结果如下:
Views
=====
1900
10992
10004
280
18
4015
...
这是我的代码:
/**
* Add view counts to admin columns
*/
add_filter( \'manage_posts_columns\', \'eri_posts_column_views\' );
function eri_posts_column_views( $columns ) {
$columns[\'post_views\'] = \'Views\';
return $columns;
}
add_action( \'manage_posts_custom_column\', \'eri_posts_custom_column_views\' );
function eri_posts_custom_column_views( $column ) {
if ( $column === \'post_views\') {
$post_id = get_the_ID();
$meta_key = \'eri_post_view_count\';
$count = 0;
if (get_post_meta( $post_id, $meta_key, true ) && get_post_meta( $post_id, $meta_key, true ) != \'\') {
$count = get_post_meta( $post_id, $meta_key, true );
}
echo $count;
}
}
/**
* Make admin columns sortable
*/
add_filter(\'manage_edit-post_sortable_columns\', \'eri_view_count_sortable_column\');
function eri_view_count_sortable_column($columns){
$columns[\'post_views\'] = \'post_views\';
return $columns;
}
add_action( \'pre_get_posts\', \'eri_view_count_custom_orderby\' );
function eri_view_count_custom_orderby( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get( \'orderby\');
if( \'post_views\' == $orderby ) {
$query->set(\'meta_key\',\'eri_post_view_count\');
$query->set(\'orderby\',\'meta_value_num\');
}
}
我试过换衣服
meta_value_num
到
meta_value
... 不工作。