Join the Voxel Guide Community!

Get Involved

Ability to Show Users "Post Read Status"

Description/Instructions

These snippets will add the functionality for people to “Record” if they have seen a post or not. Works for both logged in and non-logged in users (non logged in through cookies so it will eventually expire). Change the text to whatever you want.

If this snippet helped, feel free to buy me a taco :)

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');

 

  • PHP
Copy Code

function markPostAsRead(postId) {
let readPosts = JSON.parse(localStorage.getItem('readPosts') || '[]');
if (!readPosts.includes(postId)) {
readPosts.push(postId);
localStorage.setItem('readPosts', JSON.stringify(readPosts));
}
}

function showReadStatus(postId) {
let readPosts = JSON.parse(localStorage.getItem('readPosts') || '[]');
if (readPosts.includes(postId)) {
document.write('

You have read this post.

');
} else {
document.write('

You have not read this post.

');
}
}

  • JS
Copy Code

Instructions

Shortcode to add to the preview card.

[read_status]

  • HTML
Copy Code

Let's Chat About this Snippet

Chat Toggle
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Ask me anything about Voxel!
Send
Powered by AI24