【问题标题】:Wordpress . How to display the views a post has?WordPress 。如何显示帖子的浏览量?
【发布时间】:2017-10-12 01:05:49
【问题描述】:

代码不是我的,我在 Youtube 教程中找到的。 我想要的是显示帖子的浏览量,但只需单击并输入帖子即可。 我每次刷新页面时都会添加视图的功能,那么如果我还没有点击帖子,为什么它会添加视图? 谁能帮我解决这个问题?

这是我的函数文件中的内容

    // Views per post/page
//// Add counts views per post by refreshing(F5) the current post
//Set the Post Custom Field in the WP dashboard as Name/Value pair 
function addview($post_ID) {

    //Set the name of the Posts Custom Field.
    $count_key = 'post_views_count'; 

    //Returns values of the custom field with the specified key from the specified post.
    $count = get_post_meta($post_ID, $count_key, true);

    //If the the Post Custom Field value is empty. 
    if($count == ''){
        // $count = 0; // set the counter to zero.

        //Delete all custom fields with the specified key from the specified post. 
        delete_post_meta($post_ID, $count_key);

        //Add a custom (meta) field (Name/value)to the specified post.
        add_post_meta($post_ID, $count_key, '0');
        return $count . ' View';

    //If the the Post Custom Field value is NOT empty.
    }else{
        $count++; //increment the counter by 1.
        //Update the value of an existing meta key (custom field) for the specified post.
        update_post_meta($post_ID, $count_key, $count);

        //If statement, is just to have the singular form 'View' for the value '1'
        if($count == '1'){
        return $count . ' View';
        }
        //In all other cases return (count) Views
        else {
        return $count . ' Views';
        }
    }
}

这就是我在索引和单个文件中的内容:

<?php if(function_exists('addview')) { echo addview(get_the_ID()); }?>

【问题讨论】:

  • 使用像 Post Views Counter 这样的插件,它已经拥有所有这些功能,可以为您完成。通常,您会设置一个 cookie 或瞬态以在用户访问该页面时进行记录,这样就不会进一步刷新页面来增加计数器。 en-au.wordpress.org/plugins/post-views-counter
  • 很抱歉回答迟了,但我已经修复了它而无需使用插件:) [wp-snippets.com/post-views-without-plugin
  • 该代码中没有任何内容可以跟踪用户正在访问该页面,因此如果同一用户多次返回,计数将增加。

标签: php wordpress function


【解决方案1】:

将此代码添加到您的functions.php

function totalView($id){
    $count = 1;
    $check = get_post_meta($id, 'count',true);
    if(!$check){
        add_post_meta($id,'count',$count,true);
    }else{
        $inc = $check+1;
        $a = update_post_meta($id,'count',$inc);
    }
    return 'Total views:&nbsp;<b>'.get_post_meta($id, 'count',true).'</b> &nbsp; times';
}

然后从您的索引、单个文件或任何其他文件中调用此函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多