Limit access to posts/pages by user roles

I’m looking for a way to protect content by user roles.

Example:

Read More

you have to be registered to view posts (frontend).

If a user is a subscriber he can read post 1, 2 and 3, but if the user is a contributor he can view post 1,2,3 and 4,5,6…

does anyone know how I can do this?

Related posts

Leave a Reply

3 comments

  1. you can use such conditions to show private posts only to logged in users with role contributor. Now you only need to make post private to make that post available for contributor.

    <?php 
        if ( have_posts() ) : while ( have_posts() ) : the_post();
            $private = get_post_custom_values("private");
            if (isset($private[0]) && $private == "true") {
    
                if ( current_user_can( 'contributor' ) ) { //passing role to it may sometime not work
                the_title();
                the_content();
                } else {            // text to show instead the post
                    echo 'this post is private, only contributor can view it';
                }
    
            } else {        // this is visible to all
                the_title();
                the_content();
            }
    
        endwhile; 
        endif; 
    ?>
    
  2. To achieve something like that you can make some posts private and show them just to the logged in users, first you need to add a custom field, you can name it “private” and value it “True”. Then add replace the default WP loop with this code snippet:

        <?php if (have_posts()) : while (have_posts()) : the_post();
    
        $private = get_post_custom_values("private");
        if (isset($private[0]) && $private == "true") {
            if (is_user_logged_in()) {
                // Display private post to logged user
            }
        } else {
            // Display public post to everyone
        }
    
    endwhile; endif; ?>