用wordpress 搭建的博客或者企業(yè)站都有著同樣的需求,就是在內(nèi)容頁面需要統(tǒng)計這個頁面的瀏覽次數(shù),以方便站長查看某個頁面的仿問題,一般對代碼不熟悉的朋友都會用到瀏覽次數(shù)統(tǒng)計插件(WP-PostViews),但是眾所周知,一個站點如果插件安裝的多了會對SEO優(yōu)化 非常不利,那么下面給大家分享一個利用代碼來實現(xiàn)這種瀏覽次數(shù)的統(tǒng)計功能。
1、在functions.php函數(shù)文件的未尾另起一行,添加如下代碼。
<?php /* Postviews start */ function getPostViews($postID){ $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return " 0 "; } return $count; } function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } /* Postviews start end*/ ?>
2、在您需要顯示統(tǒng)計瀏覽次數(shù)的頁面,例如在single.php內(nèi)容頁面中的<?php endwhile; ?>和<?php endif; wp_reset_query(); ?>循環(huán)語句的中間添加以下代碼:
<?php setPostViews(get_the_ID());?>
添加后的顯示,如:
<?php endwhile; ?> <?php setPostViews(get_the_ID());?> <?php endif; wp_reset_query(); ?>
3、最后在您需要顯示統(tǒng)計的地方添加如下代碼:
<?php echo getPostViews(get_the_ID()); ?> 次瀏覽
更多wordpress相關技術文章,請訪問wordpress教程欄目進行學習!