如何获取和显示登录用户最近阅读的帖子

时间:2017-10-10 作者:Volka Dimitrev

我想知道如何显示登录用户最常阅读的帖子并显示它们?我有一个带有用户登录的博客系统,需要在个人资料中显示他们最近阅读的文章

1 个回复
SO网友:HU ist Sebastian

为此,当有人登录阅读帖子时,首先需要保存。例如,您可以在像get\\u header这样的操作中执行此操作。

add_action(\'get_header\',\'save_single_posts_to_usermeta\');

function save_single_posts_to_usermeta(){
   if(is_single() && is_user_logged_in()){
      $user_id = get_current_user_id();
      $read_posts = get_user_meta($user_id,\'_read_posts\',true);
      $most_recent_read_post = get_user_meta($user_id,\'_most_recent_post\',true);
      if(!is_array($read_posts)){
         $read_posts = array();
      }
      if(!isset($read_posts[get_the_ID()]){
         $read_posts[get_the_ID()] = 1;
      } else {
         $read_posts[get_the_ID()] = $read_posts[get_the_ID()]+1;
      }
      update_user_meta($user_id,\'_most_recent_post\',get_the_ID());
      update_user_meta($user_id,\'_read_posts\',$read_posts);
   }
}
现在,您可以方便地在需要的地方显示它,例如使用短代码:

add_shortcode(\'most_recent_read_post\',\'show_most_recent_read_post\');

function show_most_recent_read_post($args=array()){
   if(is_user_logged_in()){
      $user_id = get_current_user_id();
      $last_read_post = get_user_meta($user_id,\'_most_recent_post\',true);
      if($last_read_post){
         return "Last Read Post:".get_the_title((int)$last_read_post);
      } else {
         return "No posts were read yet!";
      }
   } else {
      return "You must be logged in to view your last read post";
   }
}

add_shortcode(\'most_read_post\',\'get_most_read_post\');

function get_most_read_post($args = array()){
   if(is_user_logged_in()){
      $user_id = get_current_user_id();
      $most_read_posts = get_user_meta($user_id,\'_read_posts\',true);
      if(is_array($most_read_posts) && (count($most_read_posts) > 0)){
         asort($most_read_posts);
         $number = reset($most_read_posts);
         $post_id = key($most_read_posts);
         return "Your most read post is ".get_the_title($post_id)." (".$number." times)";
      } else {
         return "No posts were read yet!";
      }
   } else {
      return "You must be logged in to view your most read post";
   }
}
快乐编码,Kuchenundkakao

结束

相关推荐

对WooCommerce的Functions.php更改不起作用

我正在尝试将其添加到函数中。php。在我的另一个站点上的测试实验室中,它可以很好地添加测试信息。但在这个网站上,我试图把它添加到什么都没有发生的情况下。该网站正在使用最新的woocommerce运行一个建筑节俭主题。有什么想法吗?我基本上只是想在每个产品页面上添加一行类似于免责声明但无法添加的文本。add_action(\'woocommerce_before_add_to_cart_form\',\'print_something_below_short_description\');