-2

I want to know how to display logged in user's most read posts and display them? I have a blog system with user login and need to display their most recently READ posts on their profile

3

For that you first need to SAVE when someone logged in reads a post. You can do this for instance within an action like get_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);
   }
}

Now, you can easily display it where you need to, for example with shortcodes:

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";
   }
}

Happy Coding, Kuchenundkakao

  • hi but how can I display all the recently read posts by a single logged in user? tnx for the answer. – Volka Dimitrev Oct 10 '17 at 11:30
  • What do you mean by "recently"? The last 5,10, whatever posts? Or do you mean "the read posts within the last x days"? – kuchenundkakao Oct 10 '17 at 11:40
  • yes the last 5,10 posts. – Volka Dimitrev Oct 11 '17 at 4:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.