List all private pages user has access rights to read
I am trying to list all private pages that user has access to read. To explain in more details, below is the initial setup:
Each user has a specific role created and assigned only ability to read private pages. Then these roles are selected for specific pages to limit access to that page.
Example:
- user 1 role name = user_1_role, capabilities = Read Private Pages
- user 2 role name = user_2_role, capabilities = Read Private Pages
- Page 1, visibility set to Private, limit access to user_1_role
- Page 2, visibility set to Private, limit access to user_1_role and user_2_role
Goal:
- When user 1 is logged in, I would like to list all pages that this user is able to read. In this example that would be Page 1 only.
- For user 2 the listing would be Page 1 and Page 2 as this user is able to read both pages.
I tried following code but this is listing all existing private pages and not only those with limited access to currently logged in user:
$pages = get_pages(
array('post_status' = array( 'private' ),
));
foreach ( $pages as $page ) {
if (current_user_can( 'read_private_pages', $page-ID )) {
echo $page-post_title . br/;
}
}
Any help would be much appreciated.
EDIT: I did not mention in original post that there can be unlimited number of pages and also user roles and users. So ideally the solution should work for any number of posts, users and roles.
I tried also following code similar to the above but with the same result:
$user = wp_get_current_user();
$pages = get_pages(
array('post_status' = array( 'private' ),
));
foreach ( $pages as $page ) {
if ($user-has_cap( 'read_private_pages', $page-ID )) {
echo $page-post_title . br/;
}
}
When I try to change the capability to e.g. current_user_can( 'read_pages', $page-ID )
, it is correctly not showing any pages in the list as there is no user with read_pages permissions, just with read_private_pages. So the current_user_can()
somehow works, I just think the second parameter with $page-ID
is for some reason not taken into account.
EDIT 2: I also forgot to mention that I am using a 3rd party plugin to create roles and restrict pages, known as MembersPress, so the answer/code must be able to work in conjunction with the aforementioned plugin.