【问题标题】:Displaying most viewed posts from last 7 days with views count via Wordpress rss feed通过 Wordpress RSS 源显示过去 7 天查看次数最多的帖子
【发布时间】:2019-02-13 11:24:21
【问题描述】:

我的 WP 网站需要两个提要。一个应该是普通的 wp 帖子提要

我通过将 WP-PostViews 功能添加到 feed-rss2 进行了尝试。它有效,但我不能将输出限制为 7 7 天

get_most_viewed('post', 10);

【问题讨论】:

标签: php wordpress time view rss


【解决方案1】:

我们需要做的第一件事是创建一个函数,该函数将检测帖子查看次数并将其存储为每个帖子的自定义字段。为此,请将以下代码粘贴到主题的 functions.php 文件中。

function wpb_set_post_views($postID) {
    $count_key = 'wpb_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);
    }
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

现在你已经有了这个函数,我们需要在单个帖子页面上调用这个函数。这样,该函数就可以准确地知道哪个帖子获得了视图的功劳。为此,您需要在单个 post 循环中粘贴以下代码:

wpb_set_post_views(get_the_ID());

您应该使用 wp_head 钩子在您的标题中简单地添加跟踪器。因此,将以下代码粘贴到主题的 functions.php 文件中。放置后,每次用户访问帖子时,都会更新自定义字段。

function wpb_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    wpb_set_post_views($post_id);
}
add_action( 'wp_head', 'wpb_track_post_views');

您想在单个帖子页面上显示帖子查看次数

function wpb_get_post_views($postID){
    $count_key = 'wpb_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';
    }

Then inside your post loop add the following code:

wpb_get_post_views(get_the_ID());

如果您想按查看次数对帖子进行排序,则可以使用 wp_query post_meta 参数轻松完成。最基本的循环查询示例如下所示:

<?php 
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();

the_title();

endwhile;
?>

参考网站:https://www.wpbeginner.com/wp-tutorials/how-to-track-popular-posts-by-views-in-wordpress-without-a-plugin/

【讨论】:

  • 谢谢你,瓦西姆。但我不需要单个帖子页面上的视图。我需要在我的 rss 帖子元中显示视图,限制为过去 7 天,我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2018-03-17
  • 1970-01-01
相关资源
最近更新 更多