WordPress 文章显示阅读量(PHP代码)

WordPress 文章显示阅读量(PHP代码)

您是否正在寻找一种方法来跟踪帖子阅读而无需使用post meta的插件?虽然可能有一个插件,我们已经创建了一个快速的代码片段,您可以使用它来跟踪帖子阅读而无需使用WordPress中的post meta插件。
说明:(原文地址 https://www.isitwp.com/track-post-views-without-a-plugin-using-post-meta/)
将此代码添加到主题的functions.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);
    }
}
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

(可选)将此代码添加到WordPress管理员中显示帖子阅读的列:

// Add to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

这部分跟踪阅读代码将设置帖子阅读。只需将此代码放在WordPress循环内的single.php文件中即可。

<?php
          setPostViews(get_the_ID());
?>

关于片段缓存的注意事项:如果您正在使用像W3 Total Cache这样的缓存插件,则上面设置阅读的方法将无效,因为该setPostViews()函数永远不会运行。但是,W3 Total Cache具有称为片段缓存的功能。而不是上述内容,请使用以下内容,以便setPostViews()运行得很好,即使启用了缓存,也会跟踪所有帖子阅读。

<!-- mfunc setPostViews(get_the_ID()); --><!-- /mfunc -->

以下代码是可选的。如果要显示帖子中的观看次数,请使用此代码(想在哪显示就将此代码添加至哪)。将此代码放在循环中。

<?php
          echo getPostViews(get_the_ID());
?>

注意:如果这是您第一次在WordPress中添加代码段,请参阅我们的指南,了解如何在WordPress中正确复制/粘贴代码段,这样您就不会意外破坏您的站点。

648 Views
分享你的喜爱
linwute
linwute

我要像梦一样自由,像大地一样宽容;
在艰辛放逐的路上,点亮生命的光芒;
我要像梦一样自由,像天空一样坚强;
在曲折蜿蜒的路上,体验生命的意义;

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注