正如Gael所提到的,没有本地WordPress功能来处理这个问题,但实现起来并不太困难。
update_post_meta( $post_id, \'post_subscriber\', $user_id );
首先,我将创建post-meta来标识应该有访问权限的用户。你可能想用
Meta Boxes 或使用
Settings API. 如果有多个用户需要访问同一页面,则可能需要将其设置为
User Meta 相反,这会将代码翻转到头上一点以下。
因为我们正在做1个用户访问1个页面,所以post meta应该可以正常工作。
接下来,您需要确定是只想隐藏页面的内容,还是假装页面根本不存在。从这两个选项中选择一个,而不是两个都选。
1。隐藏内容
我们将过滤页面的内容,使其他内容都可以访问(如标题、特色图片等)。您可以将内容替换为一条消息,通知访问者他们不允许看到此内容,“不!”最好在邮件中加入登录表单,以防用户忘记提前登录。
function my_filter_content( $content ) {
    global $post;
    if ( empty( $post ) || ! is_page() ) {
        return $content;
    }
    $post_subscriber_id = get_post_meta( $post->ID, \'post_subscriber\', true );
    if ( ! $post_subscriber_id ) {
        return $content;
    }
    $user = wp_get_current_user();
    if ( $user->ID === $post_subscriber_id || user_can( $user->ID, \'administrator\' ) ) {
        return $content;
    } else {
        // Content restricted message.
        return \'Nope!\';
    }
}
add_filter( \'the_content\', \'my_filter_content\', 11 );
 2。重定向页面
此操作不允许未经授权的用户或公众看到任何内容,而是将未经授权的用户重定向到一个完全独立的页面,在该页面上可以通知他们试图错误访问某些内容。通常,在该页面上包含登录表单是一种很好的做法,以防用户有访问权限,但忘记登录。
function my_page_template_redirect() {
    // Conditions for targeting the correct content type.
    if ( is_page() ) {
        global $post;
        $post_subscriber_id = get_post_meta( $post->ID, \'post_subscriber\', true );
        // Now we know this page has restricted content.
        if ( $post_subscriber_id ) {
            // Check user is logged in.
            if ( is_user_logged_in() ) {
                $user = wp_get_current_user();
                // Check user is allowed access.
                if ( $user->ID === $post_subscriber_id || user_can( $user->ID, \'administrator\' ) ) {
                    return;
                }
            }
            // Redirect user to page explaining why they can\'t see the content.
            wp_safe_redirect( home_url( \'/access-denied/\' ) );
            die;
        }
    }
}
add_action( \'template_redirect\', \'my_page_template_redirect\' );