Using WordPress ‘current_user_can_for_blog()’ PHP function

The current_user_can_for_blog() WordPress PHP function checks if the currently logged in user has a specific capability for a specified site or blog.

Usage

Let’s say we want to check if the current user can edit posts on a specific blog. We can use the function like so:

$current_user_can_edit = current_user_can_for_blog($blog_id, 'edit_posts');

In this example, $current_user_can_edit will be a boolean that is true if the user has the ‘edit_posts’ capability for the blog specified by $blog_id, and false otherwise.

Parameters

  • $blog_id (int): The ID of the site or blog you are checking the capability for.
  • $capability (string): The name of the capability you want to check.
  • $args (mixed, optional): Additional parameters, which usually start with an object ID.

More information

See WordPress Developer Resources: current_user_can_for_blog()

This function is not deprecated and is available in all recent versions of WordPress.

Examples

Check if Current User Can Edit Posts on a Specific Blog

$blog_id = 2; // Replace with your blog ID
if (current_user_can_for_blog($blog_id, 'edit_posts')) {
    echo "User can edit posts on this blog";
} else {
    echo "User cannot edit posts on this blog";
}

Check if Current User Can Publish Posts

$blog_id = 2; // Replace with your blog ID
if (current_user_can_for_blog($blog_id, 'publish_posts')) {
    echo "User can publish posts";
} else {
    echo "User cannot publish posts";
}

Check if Current User Can Edit a Specific Post

$blog_id = 2; // Replace with your blog ID
$post_id = 123; // Replace with your post ID
if (current_user_can_for_blog($blog_id, 'edit_post', $post_id)) {
    echo "User can edit this post";
} else {
    echo "User cannot edit this post";
}

Check if Current User Can Delete a Specific Post

$blog_id = 2; // Replace with your blog ID
$post_id = 123; // Replace with your post ID
if (current_user_can_for_blog($blog_id, 'delete_post', $post_id)) {
    echo "User can delete this post";
} else {
    echo "User cannot delete this post";
}

Check if Current User Can Edit Post Meta

$blog_id = 2; // Replace with your blog ID
$post_id = 123; // Replace with your post ID
$meta_key = 'my_meta_key'; // Replace with your meta key
if (current_user_can_for_blog($blog_id, 'edit_post_meta', $post_id, $meta_key)) {
    echo "User can edit this post's meta";
} else {
    echo "User cannot edit this post's meta";
}