Function and usage of add_user_to_blog() in wordpress


Answers ( 1 )


    The add_user_to_blog() function in WordPress is designed to add a user to a specific blog within a WordPress multisite network, and to set their role on that blog. Here's a detailed explanation of its function, parameters, and return value:


    add_user_to_blog( int $blog_id, int $user_id, string $role ): true|WP_Error

    • Purpose: This function adds a specified user to a specified blog within a WordPress multisite network and assigns them a specific role on that blog.


    • When using a WordPress multisite network, you might need to add users to different blogs/sites within the network. add_user_to_blog() is used for this purpose.
    • It's important to note that this function is specifically for multisite installations.
    • The function also triggers the add_user_to_blog action, allowing developers to hook custom functionality when a user is added to a blog.


    1. $blog_id (int, required): The ID of the blog you want to add the user to. This ID corresponds to a specific site within your multisite network.
    2. $user_id (int, required): The ID of the user you are adding to the blog. This is typically the user's ID in the WordPress users table.
    3. $role (string, required): The role you want to assign to the user on that blog. WordPress roles include 'subscriber', 'contributor', 'author', 'editor', and 'administrator', each with its own set of capabilities.


    • The function returns true on successful addition of the user to the blog with the specified role.
    • It returns a WP_Error object if there are any issues, such as if the user doesn’t exist or couldn't be added to the blog for some reason (e.g., database errors, invalid user ID or blog ID, etc.).

    Sample Usage:

    Here’s how you might use add_user_to_blog() in a WordPress multisite setup:

    $blog_id = 2; // The ID of the blog you want to add the user to
    $user_id = 3; // The ID of the user you're adding
    $role = 'editor'; // The role you want to assign
    $result = add_user_to_blog( $blog_id, $user_id, $role );
    if ( is_wp_error( $result ) ) {
        // Handle the error, maybe display a message to the admin
        echo 'Error: ' . $result->get_error_message();
    } else {
        // Success, maybe display a confirmation message
        echo 'User added successfully to blog!';

    In this example, a user with the ID of 3 is being added to the blog with an ID of 2 and is being assigned the role of 'editor'. The function checks if the process was successful or if there was an error, and handles each scenario accordingly.

Leave an answer