• Resolved Dr_jAcKaSS

    (@dr_jackass)


    Hello!

    I am using this plugin to restrict users from accesing certain pages of the website unless they are asigned a specific role. That means that on page with ID XX in a “Content Permission” box, under “Limit access to the content to users of the selected roles” I have selected only a few roles that can access the content.

    What concerns the main content it works as expected out of the box – if user is not assigned a role that has had access granted, custom error message is shown. However, I have a section on some pages showing related content (on the same website). I need to create a custom logic that would check for a current user whether he/she is allowed to access that content/page. If yes, than the link to this page will be shown, otherwise not.

    So, the question is, how to check in code if current user is allowed to access a page/post with ID XX or not?

    Thanks in advance!

    • This topic was modified 5 months, 1 week ago by Dr_jAcKaSS.
    • This topic was modified 5 months, 1 week ago by Dr_jAcKaSS.
Viewing 1 replies (of 1 total)
  • Plugin Author jarekk

    (@jarekk)

    Hi @dr_jackass

    To get all roles assigned to specific post/page you can use members_get_post_roles function that returns an array of roles assigned to post/page. Here is the code snippet that you can adjust:

    // Get current user's roles
    $user = wp_get_current_user();
    $user_roles = (array) $user->roles;

    // Get roles assigned to page/post with ID - 123
    $post_id = 123;
    $page_roles = members_get_post_roles( $post_id );

    // Set page as protected
    $protected_page = true;

    foreach($page_roles as $page_role) {
    // Set page as not protected if user has role assigned to Content Permissions
    if( in_array( $page_role, $user_roles ) ) {
    $protected_page = false;
    break;
    }
    }

    if(! $protected_page) {
    // Page is not protected for current user
    }

    I hope that helps.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.