wp_insert_site
云策文档标注
概述
wp_insert_site 是一个 WordPress Hook,在站点被插入数据库后触发。它主要用于在站点创建时执行相关操作,但需注意其触发时机可能过早。
关键要点
- wp_insert_site 是一个 Action Hook,参数为 WP_Site 对象 $new_site。
- 该 Hook 在 WordPress 5.1.0 版本中引入,替代了已弃用的 wpmu_new_blog。
- 用户贡献笔记指出,wp_insert_site 触发过早,建议使用 wp_initialize_site 并设置优先级高于 100 来执行初始化任务。
代码示例
add_action( 'wp_initialize_site', 'wpdocs_action_wp_initialize_site', 900 );
/**
* Fires when a site's initialization routine should be executed.
*
* @param WP_Site $new_site New site object.
*/
function wpdocs_action_wp_initialize_site( WP_Site $new_site ) : void {
switch_to_blog( $new_site->blog_id );
// do the job
restore_current_blog();
}注意事项
避免直接使用 wp_insert_site 进行站点初始化,因为它可能在其他设置完成前触发,导致问题。优先考虑 wp_initialize_site 以确保正确时机。
原文内容
Fires once a site has been inserted into the database.
Parameters
$new_siteWP_Site-
New site object.
Source
do_action( 'wp_insert_site', $new_site );
Changelog
| Version | Description |
|---|---|
| 5.1.0 | Introduced. |
Skip to note 2 content
Per Søderlind
The hook
wpmu_new_bloggives you a deprecated notice and tells you to usewp_insert_site. Don’t do that,wp_insert_sitefires too early. Instead, use wp_initialize_site with a priority higher than100, as in:add_action( 'wp_initialize_site', 'wpdocs_action_wp_initialize_site', 900 ); /** * Fires when a site's initialization routine should be executed. * * @param WP_Site $new_site New site object. */ function wpdocs_action_wp_initialize_site( WP_Site $new_site ) : void { switch_to_blog( $new_site->blog_id ); // do the job restore_current_blog(); }