如何在单页上显示帖子视图。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\';
}
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);
}
}
// Remove issues with prefetching adding extra views
remove_action( \'wp_head\', \'adjacent_posts_rel_link_wp_head\', 10, 0);
它工作得很好,可以统计浏览量,但每次即使只有一个查看器一次又一次刷新页面,它也会统计浏览量。我想玩会话cookie,但不知道如何实现。我试图实现的是用以下函数替换第二个函数:
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{
/*
* Check the cookie is exist or not.
* If not the set cookie for some time interval and
* increase the count
*/
if(!isset($_COOKIE[\'wpai_visited_ip\']))
$count++;
update_post_meta($postID, $count_key, $count);
// Get IP address
$visit_ip_addr = $_SERVER[\'REMOTE_ADDR\'];
// Set the cookie
setcookie(\'wpai_visited_ip\', $visit_ip_addr, time()+ (60 * 1));
}
}
但它不起作用,我得到以下错误:
无法修改标题信息-标题已由C:\\xampp\\htdocs\\portfolio\\wp includes\\class.wp style.php:287)在C:\\xampp\\htdocs\\portfolio\\wp content\\themes\\portfolio\\breadcrumb中发送。php在线152
如果有人能帮我,请帮忙。当新用户在单个会话中查看我的帖子时,我只需要增加视图计数器。
最合适的回答,由SO网友:Tom 整理而成
您对getPostViews
功能看起来很好,我认为你的单曲中没有这个问题。php或面包屑。php。
但是,我会将这两个函数都移到您的函数中。php(more info here) 而不是打电话setPostViews
内单/面包屑。php,我会将其附加到WordPress操作。
<?php
//...inside your functions.php...
add_action( \'init\', \'fa_setpostviews\' );
function fa_setpostviews() {
global $post;
// Do not continue if we do not have a post ID
if ( ! isset( $post->ID ) ) {
return;
}
// Do not continue if the user is not logged in
if ( ! is_user_logged_in() ) {
return;
}
// Make sure the user is on a single post.
if ( ! is_single() ) {
return;
}
/*
* Note! The above if statements could be combined into one.
*/
$postID = $post->ID;
$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 {
if ( ! isset( $_COOKIE[\'wpai_visited_ip\'] ) ) {
$count ++;
}
update_post_meta( $postID, $count_key, $count );
$visit_ip_addr = $_SERVER[\'REMOTE_ADDR\'];
setcookie( \'wpai_visited_ip\', $visit_ip_addr, time() + ( 60 * 1 ) );
}
}
上述函数检查用户是否已登录,用户是否在单个post页面上,然后像以前一样执行计数脚本。
Note: 这是在init
钩子,这可能不是最适合你使用的钩子。Init会被多次调用,您可能希望连接到wp
相反在此处查看有关挂钩和操作的更多信息:https://codex.wordpress.org/Plugin_API/Action_Reference