显示 WordPress 上帖子的浏览次数

Kru*_*nal 4 wordpress wordpress-theming

我正在开发一个 WordPress,并使用插件 WordPress 热门帖子,并面临这个问题。

如何在博客的类别列表页面或索引页面上显示访问者查看页面的次数。此信息已经存在,插件正在使用该信息在侧边栏中显示相同的信息,不确定如何使用相同的插件数据在博客页面上显示页面浏览量。

我试图找到这个,但没有得到我想要的。

请建议如何做到这一点?

我使用的插件是http://wordpress.org/extend/plugins/wordpress-popular-posts/

Suj*_*mar 10

您无需插件即可轻松完成。

要计算帖子浏览量,您要做的第一件事是将以下代码添加到您的 WordPress 主题functions.php

<?php
/*
 * Set post views count using post meta//functions.php
 */
function customSetPostViews($postID) {
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '1');
    }else{
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

现在我们将在single.php中调用此函数来更新数据库中的计数值。

<?php 
    customSetPostViews(get_the_ID());//single.php
?>
Run Code Online (Sandbox Code Playgroud)

现在,在同一个single.php文件中,如果我们想显示帖子浏览次数,我们可以使用以下代码:

<?php
    $post_views_count = get_post_meta( get_the_ID(), 'post_views_count', true );
    // Check if the custom field has a value.
    if ( ! empty( $post_views_count ) ) {
        echo $post_views_count;
    }
?>
Run Code Online (Sandbox Code Playgroud)

现在按帖子浏览次数降序显示所有热门帖子。使用此代码:

<?php//popular post query
    query_posts('meta_key=post_views_count&posts_per_page=5&orderby=meta_value_num&
    order=DESC');
    if (have_posts()) : while (have_posts()) : the_post();
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
    endwhile; endif;
    wp_reset_query();
?>
Run Code Online (Sandbox Code Playgroud)

快乐编码