您的位置:首页 > 其它

WordPress主题开发:设置和获取浏览次数

2017-10-27 15:58 676 查看
将以下代码放在functions.php,一个是获取阅读量,一个是设置阅读量

<?php

/**
* getPostViews()函数
* 功能:获取阅读数量
* 在需要显示浏览次数的位置,调用此函数
* @Param object|int $postID   文章的id
* @Return string $count          文章阅读数量
*/
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;
}

/**
* setPostViews()函数
* 功能:设置或更新阅读数量
* 在内容页(single.php,或page.php )调用此函数
* @Param object|int $postID   文章的id
* @Return string $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 );
}
}

?>


 注意:调用了setPostViews函数后,每刷新一次就会增加一次浏览量。

在内容页(single.php,或page.php )尝试一下吧:

<?php setPostViews(get_the_ID());echo getPostViews( get_the_ID() ); ?>


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: