Hiding posts from non logged in users
I wish to hide certain posts for anyone that is not logged in. I tried the Restrict Content (RC) plugin but that did only hide the content of posts, i wish to omit the post completely.
Using RC as a foundation i tried the following:
function hideFromUnknownUsers($postObject) {
$rcUserLevel = get_post_meta ( $postObject-ID, 'rcUserLevel', true );
if(have_posts())
{
if (!(
!current_user_can ( 'read' )
(
$rcUserLevel == 'Administrator' ||
$rcUserLevel == 'Editor' ||
$rcUserLevel == 'Author' ||
$rcUserLevel == 'Contributor' ||
$rcUserLevel == 'Subscriber'
)
)) {
the_post();
}
}
}
add_action ( 'the_post', 'hideFromUnknownUsers' );
This has a systematic downside. The last post can not be ignored. I can however live with that for now.
Another problem is that this also causes an infinite loop, repeating the same posts over and over again. I found that this is because the have_posts()
does not only tell us that the end of the last post has been reached but has the side effect that the post counter is also reset preventing my main loop from reaching its end.
Making a have_posts()
that are non invasive proved difficult since i could not figure out how to reach the $wp_query-current_post
and $wp_query-post_count
from the plugin.
One solution would be having the above logic directly in the themes PHP files but that would have to be repeated everywhere i intend to access a post making it cumbersome and prone to errors.
Is there any other way to hide certain posts from unknown users?
Topic members content-restriction posts Wordpress
Category Web