Wordpress。如何显示帖子的观点?

时间:2017-10-12 01:05:49

标签: php wordpress function

代码不是我的,我在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()); }?>

1 个答案:

答案 0 :(得分:0)

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

{ 
"_id" : ObjectId("59dce1f92d57920d3e62bdbc"), 
"updatedAt" : ISODate("2017-10-10T15:06:34.111+0000"), 
"createdAt" : ISODate("2017-10-10T15:06:33.996+0000"), 
"_customer" : ObjectId("59dce1f92d57920d3e62bd44"), 
"_distributor" : ObjectId("59dce1f92d57920d3e62bd39"), 
"status" : "NEW", 
"cart" : [
    {
        "count" : NumberInt(1), 
        "_item" : ObjectId("59dce1f92d57920d3e62bd57"), 
        "_id" : ObjectId("59dce1f92d57920d3e62bdc1")
    }, 
    {
        "count" : NumberInt(1), 
        "_item" : ObjectId("59dce1f92d57920d3e62bd5c"), 
        "_id" : ObjectId("59dce1f92d57920d3e62bdc0")
    }, 
    {
        "count" : NumberInt(1), 
        "_item" : ObjectId("59dce1f92d57920d3e62bd61"), 
        "_id" : ObjectId("59dce1f92d57920d3e62bdbf")
    }, 
    {
        "count" : NumberInt(1), 
        "_item" : ObjectId("59dce1f92d57920d3e62bd66"), 
        "_id" : ObjectId("59dce1f92d57920d3e62bdbe")
    }, 
    {
        "count" : NumberInt(1), 
        "_item" : ObjectId("59dce1f92d57920d3e62bd6b"), 
        "_id" : ObjectId("59dce1f92d57920d3e62bdbd")
    }
], 
"_upstreamOrders" : [
    "4545643499"
], 
"key" : "4592846350", 
"__v" : NumberInt(1), 
"_invoice" : "0811260909610702"

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