之前文章大挖和大家分享過怎樣在wordpress后臺列表添加文章閱讀數(shù)量,今天分享一個升級版,同時在wordpress模板列表后臺顯示閱讀與點贊的數(shù)量,通過列表就直觀的可以看到當前文章的閱讀情況及點贊情況,更好方便站長對文章內(nèi)容方向做統(tǒng)計。
其實添加閱讀與添加點贊的原理是相通的,假如你還想加其他的數(shù)據(jù),增加對應的字段就可以了。
將以下代碼復制到functions.php中即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
//~ 數(shù)字 格式化 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列數(shù)據(jù),展示瀏覽量和點贊數(shù) add_filter( 'manage_posts_columns', 'hbao_customer_posts_columns' ); function hbao_customer_posts_columns( $columns ) { $columns['views'] = '瀏覽量'; $columns['likes'] = '點贊數(shù)'; return $columns; } //~ 輸出瀏覽量和點贊數(shù) 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是字段名,根據(jù)你自己的來 if(!$count){ $count = 0; } echo $count; } if($column=='likes'){ $likes_count = get_post_meta($post_id,'bigfa_ding',true); // 注意 bigfa_ding是字段名,根據(jù)你自己的來 if(!$likes_count) { $likes_count = 0; } echo $likes_count; } return; } |
擴展閱讀,get_post_meta函數(shù)
1 |
get_post_meta( int $post_id, string $key = '', bool $single = false ) |
使用方法:
1 |
<?php $meta_values = get_post_meta($post_id, $key, $single); ?> |
參數(shù):
$post_id
(int) (Required) Post ID.
(整數(shù)) (必須的)包含此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, 則返回一個數(shù)組字符串型。
參考資料:https://developer.wordpress.org/reference/functions/get_post_meta/