Display Private Posts to Logged in Users

WordPress-Christmas-15Sometimes I use the function of private posting in WordPress. These contributions can only see the user who has created the post, or the administrator. To show all these article to users who are logged into the system, you can go different ways. But I’d like to highlight just two different ways.

With custom fields

With the help of custom fields you create a private field; if you can see private posts, this field has true in the field. This field, we then query in the loop on output in the frontend.

if ( have_posts() ) :
	while ( have_posts() ) : the_post();
	// the loop
	$private = get_post_custom_values('private'); // read custom field
	if ( isset($private[0]) && $private == 'true' ) {
		if ( is_user_logged_in() ) {
			// display private post, only logged users
		}
	} else {
		// display public post, for every visitors
	}

	endwhile;
endif;

With capabilities

Another method is, to assign via function capabilities to the appropriate role. You can do this with the help of a Plugin, for example Members, or just with a code snippet in functions.php of the theme. You have to call the snippet just once, after that you can delete it, since the capability is saved in the data base.

Ad capabilities to read private posts read_private_posts to the role of the author.

function fb_add_cap2role() {
	global $wp_roles;
	
	$wp_roles->add_cap('author', 'read_private_posts');
}
add_action( 'init', 'fb_add_cap2role' );

Also you can also remove the rights again. This is possible with the following solution:

function fb_remove_cap2role() {
	global $wp_roles;
	
	$wp_roles->remove_cap('author', 'read_private_posts');
}
add_action( 'init', 'fb_remove_cap2role' );

Posted

in

by

Comments

One response to “Display Private Posts to Logged in Users”

  1. Alt Design Avatar

    Can’t understand why you’re using a custom field “private”… Maybe i’m wrong but… how about do something like this:

    if ($post->status == ‘private’ ) {
    if ( is_user_logged_in() ) {
    // display private post, only logged users
    }
    } else {
    // display public post, for every visitors
    }