wordpress - 显示 WordPress 上帖子的浏览次数

标签 wordpress wordpress-theming

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

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

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

请告诉我如何做到这一点?

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

最佳答案

无需插件即可轻松完成。

要计算帖子浏览量,您要做的第一件事就是将以下代码添加到您的 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);
    }
}
?>

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

<?php 
    customSetPostViews(get_the_ID());//single.php
?>

现在,在同一个 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;
    }
?>

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

<?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();
?>

快乐编码

关于wordpress - 显示 WordPress 上帖子的浏览次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12934161/

相关文章:

MySql 查询通过 rand() 从 limit 和 order 中获取一定数量的值

php - WordPress插件开发

wordpress - 将 robots.txt 保持为空白

css - 如何在不弄乱所需样式的情况下移动箭头

php - Bogo 插件 : Post in alternative language appears on blog despite draft, 预定或 bin 状态

php - WordPress - 在编写创建动态类的函数时,如何根据顶级父名称定位子页面?

html - 如何使用与没有帖子计数不同的帖子计数来设置小部件的样式

php - wordpress永久链接重新加载页面而不是重定向到帖子

html - Bootstrap 的中心 block 不工作

css - 如何在 Bootstrap 4 中均匀分布 Navbar 元素