本文章下面來給各位同學介紹一下Wordpress實現php代碼版文章瀏覽數,這里就可以瀏覽到每篇文章的具體瀏覽資料了,如果需要更詳細的我們可使用WP-Postviews 這款插件來統計文章瀏覽數了.
我個人只要“統計和輸出瀏覽數”功能,所以挪用了主體函數部分,代碼如下:
- function custom_the_views($post_id, $echo=true, $unit=' views') {
- $count_key = 'views';
- $views = get_post_custom($post_id);
- $views = intval($views['views'][0]);
- if ($views == '') {
- return '';
- } else {
- if ($echo) {
- echo number_format_i18n($views) . $unit;
- } else {
- return number_format_i18n($views) . $unit;
- }
- }
- }
- function set_post_views() {
- global $post;
- $post_id = intval($post->ID);
- $count_key = 'views';
- $views = get_post_custom($post_id);
- $views = intval($views['views'][0]);
- if (is_single() || is_page()) {
- if(!update_post_meta($post_id, 'views', ($views + 1))) {
- add_post_meta($post_id, 'views', 1, true);
- }
- }
- }
- add_action('get_header', 'set_post_views');
參數說明:
1. $post_id: 文章ID,一般填 $post->ID
2. $echo: true/false,顯示/獲取瀏覽數(默認是顯示-true)
3. $views: 瀏覽數單位(默認是:空格+views)
一般調用方法,代碼如下:
<?php if ( function_exists('custom_the_views') ) custom_the_views($post->ID);?>
提示:如果原來用了 WP-Postviews 這個插件,只要把如下代碼:
<?php the_views(); ?> 改為 <?php custom_the_views($post->ID); ?>即可。
或者是如下代碼:
<?php if ( function_exists('the_views') ) the_views(); ?>
改為:<?php if ( function_exists('custom_the_views') ) custom_the_views($post->ID);
新聞熱點
疑難解答
圖片精選