function mark_post_as_read() {
if (is_single()) {
global $post;
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$read_posts = get_user_meta($user_id, 'read_posts', true);
$read_posts = empty($read_posts) ? array() : (array) $read_posts;
if (!in_array($post->ID, $read_posts)) {
$read_posts[] = $post->ID;
update_user_meta($user_id, 'read_posts', $read_posts);
}
} else {
// Non-logged-in users: use JavaScript (below) to handle local storage
echo 'markPostAsRead(' . $post->ID . ');';
}
}
}
add_action('wp', 'mark_post_as_read');
function show_read_status() {
global $post;
$output = '
You have not read this post.
';
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$read_posts = get_user_meta($user_id, 'read_posts', true);
if (is_array($read_posts) && in_array($post->ID, $read_posts)) {
$output = '
You have read this post.
';
}
} else {
// Non-logged-in users: JavaScript will handle showing the status
$output .= 'showReadStatus(' . $post->ID . ');';
}
return $output;
}
add_shortcode('read_status', 'show_read_status');