You’re calling get_post_meta()
in two different ways: the first, leaving $single
unset (it defaults to false
) will get you the full array of meta entries for the given key; the second, setting $single
to true
, will get only the first item with that key.
What you want, I believe, is an array of user IDs attached to each post in the post_is_read
meta.
Here’s how I’d attack the problem:
single page template
// Get the list of readers.
$readers = get_post_meta( get_the_ID(), 'post_is_read', true );
// If the value is empty, make sure it's an array.
if ( empty( $readers ) ) {
$readers = array();
}
$current_user = wp_get_current_user();
if ( ! in_array( $current_user->ID, $readers ) ) {
// Adds the current user ID to the $readers array.
$readers[] = $current_user->ID;
// Updates the 'post_is_read' meta.
update_post_meta( get_the_ID(), 'post_is_read', $readers );
}
posts loop
$readers = get_post_meta( get_the_ID(), 'post_is_read', true );
if ( empty( $readers ) ) {
$readers = array();
}
$current_user = wp_get_current_user();
if ( ! in_array( $current_user->ID, $readers ) ) {
// If the current user hasn't read the post, make a note of it.
echo 'unread post';
}