我猜你在用wp_insert_post()
为用户创建专用页。函数返回所创建页面的ID。您可以将此ID用作授予用户的自定义功能的一部分。
// 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);
}
当用户尝试访问专用页时,请使用
user_has_cap
筛选以检查用户是否具有所需的自定义cap并动态授予私有页面读取能力。
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;
}