钩子文档

add_user_to_blog

💡 云策文档标注

概述

add_user_to_blog 是一个 WordPress 动作钩子,在用户被添加到站点后立即触发。它主要用于多站点网络环境,允许开发者在用户添加时执行自定义操作。

关键要点

  • 这是一个动作钩子,触发时机为用户被添加到站点后。
  • 参数包括 $user_id(用户ID)、$role(用户角色)和 $blog_id(站点ID)。
  • 常用于多站点网络,例如自动将用户添加到多个子站点。

代码示例

/**
 * Add a user to network sites.
 *
 * @param int $user_id User ID.
 */
function wpdocs_add_user_to_network_sites( $user_id ) {

    // Put common sites here
    $blogs = array( 1, 2, 3, 5,8 ); 
  
    foreach ( $blogs as $blog ) {
        add_user_to_blog( $user_id, $blog, 'subscriber' );
    }
}
add_action( 'user_register', 'wpdocs_add_user_to_network_sites' );

📄 原文内容

Fires immediately after a user is added to a site.

Parameters

$user_idint
User ID.
$rolestring
User role.
$blog_idint
Blog ID.

Source

do_action( 'add_user_to_blog', $user_id, $role, $blog_id );

Changelog

Version Description
MU (3.0.0) Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Here is a use case when you may need to add users to common sites (forums, support trackers etc ) on the network apart from the main site and their own site(s).

    /**
     * Add a user to network sites.
     *
     * @param int $user_id User ID.
     */
    function wpdocs_add_user_to_network_sites( $user_id ) {
    
    	// Put common sites here
    	$blogs = array( 1, 2, 3, 5,8 ); 
      
    	foreach ( $blogs as $blog ) {
    		add_user_to_blog( $user_id, $blog, 'subscriber' );
    	}
    }
    add_action( 'user_register', 'wpdocs_add_user_to_network_sites' );