Assign a post to a user

As Gail mentioned, there isn’t native WordPress functionality to handle this, but it’s not too difficult to achieve.

update_post_meta( $post_id, 'post_subscriber', $user_id );

First, I would create the post meta that identifies the user who should have access. You’ll probably want to set it with meta boxes on individual pages or using the Settings API. If you have more than one user that needs access to the same page, you may want to set this as a user meta, which will flip the code on its head down a bit.

Since we are doing 1 user accesses 1 page, the post meta should work fine.

Next, you need to determine whether you just want to hide the content of the page or pretend that the page doesn’t even exist. Choose one of these, not both.

We will filter the content of the page, leaving everything else accessible (such as the title, featured image, etc. You can replace the content with a message notifying the visitor that they are not allowed to view this content,” No!” It’s a good practice to include a login form with your message in case the user forgets to log in ahead of time.

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 );

Instead of allowing unauthorized users or the public to see anything, this action redirects unauthorized users to an entirely different page where they can be notified that they tried to access something by mistake. If the user has access but has forgotten to log in, it is generally a good practice to include a login form on this page.

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' );

Leave a Comment