• Resolved swaip

    (@swaip)


    Hi,

    And thanks for this plugin!

    I’m using it to restrict access to some frontend pages based on user roles.
    This works in preventing users to access the content on the page.

    However,I would like to automatically redirect these users to a login page, if they do not belong to any of the allowed user roles for that page. Would that be possible via code?
    Something like :

    if
    user is not in list of allowed roles for THIS page)
    then
    redirect to specific page

    Thanks,

    Carlo

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Caseproof

    (@caseproof)

    Hi Carlo,

    Members doesn’t allow to redirect unauthorized users from protected page, but you can use this code snippet at the end of your theme’s functions.php file to do that:

    add_action( 'template_redirect', function() {
      // Redirect users from specific page 
      // when user doesn't have particular role 
      $user = wp_get_current_user();
      if ( is_page(array('contact', 'about')) && ( ! is_user_logged_in() || ( ! empty($user) && in_array( 'author', (array) $user->roles ) ) ) ) {
        $redirect = 'https://your-domain.com/wp-login.php'; // Change this to the correct URL
        wp_redirect( $redirect );
        exit;
      }
    } );

    All you need to do is change pages list in 'contact', 'about' array, and role in author string.

    Hopefully, that helps.

    Thread Starter swaip

    (@swaip)

    Hi,

    and thanks for your answer.

    Actually I am trying to understand if there’s any function that returns the list of authorized roles for the current page so that I can check if the current user role is in the array of authorized roles for the page.

    Another way around that would be to add a custom capability and then check for that capability, but I still don’t understand if it’s possible to add custom capabilities in Members.

    Thanks !

    Plugin Author Caseproof

    (@caseproof)

    Hi @swaip

    You can use members_get_post_roles that gets post ID as an argument and returns an array of the roles for a given post

    Hopefully, that helps.

    Thread Starter swaip

    (@swaip)

    THANKS!
    That was exactly the function I was searching for. I then made an in_array check for the user role inside the allowed roles and a wp_redirect if not allowed.
    Works like a charm, I don’t understand though why this is not the default behaviour of the plugin.

    Thanks again !

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘List of allowed user roles on current page’ is closed to new replies.