Roles and capabilities are used to control access and normally you should use them.
For example, capabilities edit_other_posts
and edit_published_posts
are needed to edit other user’s posts.
It’s the same with othe types (pages -> edit_other_pages
, edit_published_pages
).
Since, besides limiting the right to change other user’s posts, you also want them to be invisible, you probably need to use the solution as above.
Function se333732_pre_get_post
is used to filter the list of posts in the administration, while the se333732_load_post
redirects the user if he opened the edit page (guessing post number) but he doesn’t have access to it.
add_action( 'pre_get_posts', 'se333732_pre_get_post' );
add_action( 'load-post.php', 'se333732_load_post' );
function se333732_pre_get_post( $query )
{
if ( !is_admin() )
return;
$cfg_limited_access = se333732_roles_and_types();
if ( $query->is_main_query() && in_array($query->query_vars['post_type'], $cfg_limited_access['post_types']) )
{
$user = wp_get_current_user();
if ( !array_intersect( $cfg_limited_access['privileged_roles'], $user->roles ) )
$query->query_vars['author'] = get_current_user_id();
}
}
function se333732_load_post()
{
if ( isset($_GET['post']) && (int)$_GET['post'] == $_GET['post'] )
{
$post_id = (int)$_GET['post'];
$post = get_post( $post_id );
if ( $post )
{
$author_id = $post->post_author;
$post_type = $post->post_type;
$user = wp_get_current_user();
$cfg_limited_access = se333732_roles_and_types();
if ( $author_id != $user->ID
&& in_array( $post_type, $cfg_limited_access['post_types'] )
&& !array_intersect( $cfg_limited_access['privileged_roles'], $user->roles ) )
{
wp_redirect( admin_url("edit.php?post_type=$post_type") );
}
}
}
}
function se333732_roles_and_types()
{
return [
'privileged_roles' => [ 'editor', 'administrator' ],
'post_types' => [ 'page', 'post', 'shop_order' ],
];
}