I did something similar once.
I needed to attach one or more CPT to specific customers.
I made a searchable select box containing all users in the edit screen of the CPT only available to admins.
The admin would create the post, save it, and then change the author of the post to the desired customer username.
The reason I chose to go this way is because a post cannot assigned to a user, unless that user is it's author. You could also try to add a metabox to your post type which will contain the authorized users for your post to filter by meta key. But by using this method you can easily filter using the main query. It's just a matter of changing the ownership of your post. I guess it all depends on the nature of your project.
Then I had a script which filtered the posts something like this.
Note that this code is a general idea. Writing from what I remember.
add_action( 'pre_get_posts', 'wpse_show_user_posts');
function wpse_show_user_posts( $query ){
// Don't filter if user is an administrator
if ( current_user_can( 'list_users' ) )
return;
// Get all posts which our current user is an author for
if( is_user_logged_in() && $query->is_main_query() ){
$current_user = wp_get_current_user();
$query->set( 'author', $current_user->ID );
}
// Hide all posts otherwise
if( $query->is_main_query() ) {
$query->set( 'category__not_in', '1' ); // Use the id of the retricted category
}
return $query;
}
Of course you might want to use custom roles with appropriate capabilities so you have better control on what your users can do. Know that any users can be the post authors, but the default author metabox select field on a post edit screen will only return users with at least contributor roles (which also have delete_posts capability). So that is why I created a custom select box returning the users from my custom role.
You might also only return that restricted content only to logged in users.
add_filter( 'the_content', 'logged_in_only' );
function logged_in_only( $content ){
$categories = get_the_category();
$cat_not_in = 'some-cat';
$include_post = true;
foreach( $categories as $category ){
if( $category->slug == $cat_not_in )
$include_post = false;
}
if( is_user_logged_in() || $include_post ) {
return $content;
}
return 'You need to log in <a href="' . home_url( 'wp-login.php') . '">Here</a>';
}
You would need to create a restricted
category and assign the posts you wish to control to that category in order to properly filter those posts to users not logged in.