Search code examples
wordpresswordpress-themingcustom-wordpress-pagesposts

Wordpress how to show logged in users that they have read a post


Is there a way to show logged in users that they have already read a post?

Even with a "mark as read" button?


Solution

  • add below code to your theme function.php file its save all user read post data

    add_action('wp_head', function () {
       $user_id = get_current_user_id();
       # if user is logged in 
       if (!empty($user_id)) {
           $post_id = get_the_ID();
           $user_read_post = get_user_meta($user_id, 'read_posts', true);
           if (empty($user_read_post)) {
              $user_read_post = array(); // if there is no read post 
            }
    
            if (!empty($post_id)) {
                array_push($user_read_post, $post_id);
            }
            $user_read_post = array_unique($user_read_post);
            update_user_meta($user_id, 'read_posts', $user_read_post);
        }
    });
    

    how to retrieve user read post

     $user_id = get_current_user_id();
     # if user is logged in 
       if (!empty($user_id)) {
           $user_read_post = get_user_meta($user_id, 'read_posts', true);
     }