【问题标题】:Wordpress post views count twiceWordpress 帖子浏览次数计数两次
【发布时间】:2017-08-19 15:52:34
【问题描述】:

我创建了帖子视图功能。但我有一个问题。每次页面刷新我的函数计数两次。 0,2,4,6,8...提前谢谢你。

我的函数.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;
}

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);
    }
}


add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = 'Views';
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
 if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

我的single.php:

get_header();
if(function_exists('getPostViews')) { echo getPostViews(get_the_ID()); }

while ( have_posts() ) : the_post();

if(function_exists('setPostViews')) { setPostViews(get_the_ID()); }      

the_content(); 

endwhile;

get_footer();

我认为我的 single.php 循环了两次。希望对你们有帮助。

【问题讨论】:

    标签: wordpress post view count


    【解决方案1】:

    在你的functions.php中添加这一行以消除预取添加额外视图的问题

    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
    

    还要确保您的header.php 中不存在此行,因为没有设置路径,Chrome 实际上会尝试第二次点击同一页面以获取快捷方式图标。

    <link rel="shortcut icon" href="" />
    

    另一种解决方案

    在循环查询结束时重置所有查询,使用这个标签 wp_reset_query();

    【讨论】:

    • 感谢您的回答。我都试过了,但还是不行。我创建了这样的自定义 css: wp_add_inline_style( $handle, $custom_css );此行导致错误。
    • 使用这个标签 wp_reset_query(); 在循环查询结束时重置所有查询
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多