Make a single page in WordPress available only for Admin and Subscribers

I'm trying to make a single page only available for administrator and subscribers from the site. I've put the page as private in WordPress admin and tried to allow that only for these two roles using the code above but it is not working properly. Any help will be appreciated.

?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( 'administrator' ) ) { 
        the_title();
        the_content();
        } else if ( current_user_can( 'subscriber' ) )  {
                the_title();
                the_content();
               } else  {            // text to show instead the post
                    echo 'this post is private';
        }


    } else {        // this is visible to all
        the_title();
        the_content();
    }

endwhile; 
endif; 
?

I've also tried:

I've tried it also, but with no success:

?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('subscriber') || current_user_can('administrator') )  {
            the_title();
            the_content();
        }      

    } else {        // this is visible to all
        echo 'This post is private.';
      }

 endwhile;
endif;
?

But also with no success.

Topic user-roles page-specific-settings permissions Wordpress

Category Web


please try this

if ( have_posts() ) : while ( have_posts() ) : the_post();
   if ( get_post_status (get_the_id()) == 'private' ) {
     if ( current_user_can( 'administrator' ) ) { 
        the_title();
        the_content();
     } else if ( current_user_can( 'subscriber' ) )  {
        the_title();
        the_content();
     } else  {
        echo 'this post is private';
     }
    } else {
        the_title();
        the_content();
    }

endwhile; 
endif;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.