I assume you’re using wp_insert_post()
to create the private page for the user. The function returns the ID of the created page. You can use this ID as part of a custom capability you grant to the user.
// create the new $user
// create private page
$private_page_id = wp_insert_post( $postarr, $wp_error = false ); // returns id on success, 0 on failure
if ( $private_page_id ) {
// grant custom cap
$user->add_cap("can_access_{$private_page_id}", true);
}
When user tries to access the private page, use user_has_cap
filter to check, if the user has the required custom cap and dynamically grant the private page reading capability.
add_filter('user_has_cap', 'user_can_access', 10, 4);
function user_can_access($allcaps, $caps, $args, $user) {
$object = get_queried_object();
// make sure we're on a post
if ( ! is_a($object, 'WP_Post') ) {
return $allcaps;
}
// it should be a private page post
if ( 'page' !== $object->post_type || 'private' !== $object->post_status ) {
return $allcaps;
}
// does the user have the required access cap?
$can_access="can_access_" . $object->ID;
if ( isset( $allcaps[$can_access] ) && true === $allcaps[$can_access] ) {
// if so, allow user to access the private content
$allcaps['read_private_pages'] = true;
}
return $allcaps;
}