我正在尝试显示没有插件的帖子类型视图。
例如(33次观看)
我的帖子类型是投资组合。知道如何用每个帖子显示这些视图吗?
答案 0 :(得分:1)
我使用以下内容显示帖子视图。
function setPostViews($postID) {
$user_ip = $_SERVER['REMOTE_ADDR']; //retrieve the current IP address of the visitor
$key = $user_ip . 'x' . $postID; //combine post ID & IP to form unique key
$value = array($user_ip, $postID); // store post ID & IP as separate values (see note)
$visited = get_transient($key); //get transient and store in variable
//check to see if the Post ID/IP ($key) address is currently stored as a transient
if ( false === ( $visited ) ) {
//store the unique key, Post ID & IP address for 12 hours if it does not exist
set_transient( $key, $value, 60*60*12 );
// now run post views function
$count_key = 'views';
$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);
}
}
}
此功能检查IP并存储它。瞬态设置为12小时,因此如果用户在12小时内再次访问该页面,则不会将其视为另一个视图。您需要在循环内的任何位置<?php setPostViews(get_the_ID()); ?>
添加以下代码single.php
。
以下函数将显示帖子视图。您可以自定义此项以更改输出文本
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 View";
}
return $count.' Views';
}
只需在需要显示帖子视图的地方添加<?php echo getPostViews(get_the_ID()); ?>