0

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.

  • I've tried it also, but with no success: – Marcelo Srougi Apr 7 '17 at 7:27
1

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;
  • It shows the page correctly for administrator but when I'm subscriber or other role different from administrator it redirects me to home. – Marcelo Srougi Apr 6 '17 at 14:35
  • Your redirection may be happening from any other redirection code this code is not responsible for any redirection So please check your code if you found something for the same. – kamleshpal Apr 7 '17 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.