WordPress后台文章列表加入文章点赞数、阅读数
通常大部分主题只会在前台页面有阅读数、点赞数等相关功能,那么在WordPress后台的文章列表同时也想显示文章阅读数量和点赞的数量要如何实现?,往下看
通过后台列表就直观的可以看到当前文章的阅读情况及点赞情况,更好地方便站长对每篇文章内容方向做统计分析。

其实添加阅读与添加点赞的原理是相通的,假如你还想加其他的数据,增加对应的字段就可以了。
将以下代码复制到functions.php中即可。
//~ 数字 格式化
function num2tring($num) {
if ($num >= 10000) {
$num = round($num / 10000 * 100) / 100 .' w'; // 以万为单位
} elseif($num >= 1000) {
$num = round($num / 1000 * 100) / 100 . ' k'; // 以千为单位
} else {
$num = $num;
}
return $num;
}
//~ 在后台文章列表增加2列数据,展示浏览量和点赞数
add_filter( 'manage_posts_columns', 'hbao_customer_posts_columns' );
function hbao_customer_posts_columns( $columns ) {
$columns['views'] = '浏览量';
$columns['likes'] = '点赞数';
return $columns;
}
//~ 输出浏览量和点赞数
add_action('manage_posts_custom_column', 'hbao_customer_columns_value', 10, 2);
function hbao_customer_columns_value($column, $post_id){
if($column=='views'){
$count = num2tring(get_post_meta($post_id,'post_views_count',true)); // 注意 post_views_count是字段名,根据你自己的来
if(!$count){
$count = 0;
}
echo $count;
}
if($column=='likes'){
$likes_count = get_post_meta($post_id,'bigfa_ding',true); // 注意 bigfa_ding是字段名,根据你自己的来
if(!$likes_count) {
$likes_count = 0;
}
echo $likes_count;
}
return;
}
扩展阅读,get_post_meta函数
get_post_meta( int $post_id, string $key = '', bool $single = false )
使用方法:
<?php $meta_values = get_post_meta($post_id, $key, $single); ?>
参数:
$post_id
(int) (Required) Post ID.
(整数) (必须的)包含此meta文章的ID
$key
(string) (Optional) The meta key to retrieve. By default, returns data for all keys.
(字符串) (必须的) 此meta的名称
$single
(bool) (Optional) Whether to return a single value.
(布尔型) (可选) 如果设为true, 则返回单个的meta的值。如果设为false, 则返回一个数组字符串型。
参考资料:https://developer.wordpress.org/reference/functions/get_post_meta/