如何在While循环中显示每个帖子的阅读次数?

时间:2012-10-02 作者:Derfder

我的header.php 它正在发挥作用:

<div id="news">
        <?php query_posts(\'category_name=news\'); ?>
        <?php while (have_posts()) : the_post(); ?>
            <div class="new">
                <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail(\'thumbnail\'); ?>
                </a>
                <a href="<?php the_permalink(); ?>">
                    <h3><?php the_title(); ?></h3>
                </a>
                <?php the_excerpt(); ?>
                <p>
                    <span class="autor">Author: <?php the_author(); ?></span>&nbsp;|&nbsp;
                    <span class="autor">Date: <?php the_date(); ?></span>&nbsp;|&nbsp;

                </p>

            </div>

        <?php endwhile; ?>
</div>
现在,我想做一些类似的事情:

<span class="views">Views: <?php the_views(); ?></span>&nbsp;|&nbsp;
显示每篇文章的阅读次数。然而,它抛出了一个错误。如何解决这个问题?

2 个回复
最合适的回答,由SO网友:Stephen Harris 整理而成

the_views() 不是WordPress的内置功能。事实上,默认情况下,WordPress不会记录帖子的视图数。

可能有几个插件添加了此功能。我使用过的唯一一个(我从来没有遇到过任何问题)是WP Postviewshttp://wordpress.org/extend/plugins/wp-postviews/.

SO网友:Shady M Rasmy

在功能中。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);
}}
然后是单曲。php放入此代码<?php setPostViews(get_the_ID()); ?>

若要显示视图计数,请将此代码放在所需的任何位置<span class="views"><?php echo getPostViews(get_the_ID()); ?></span>&nbsp;|&nbsp;这将计算每次访问该帖子的次数,您可以将其放入循环中。php/索引。phpto查看每个帖子视图

结束

相关推荐