activate_plugins()
云策文档标注
概述
activate_plugins() 函数用于批量激活 WordPress 插件,支持单个插件或插件列表,并可配置重定向、网络范围激活和静默模式。
关键要点
- 函数接受 $plugins 参数(字符串或数组)指定要激活的插件,$redirect 参数用于成功激活后的页面重定向,$network_wide 参数控制是否在网络范围内启用插件,$silent 参数可阻止调用激活钩子。
- 执行过程中,如果任一插件路径无效或激活出错,函数会立即停止并返回 WP_Error 对象,错误信息包含具体插件和错误详情。
- 函数内部通过循环调用 activate_plugin() 处理每个插件,收集错误,最终返回 true 表示成功或 WP_Error 表示失败。
代码示例
function activate_plugins( $plugins, $redirect = '', $network_wide = false, $silent = false ) {
if ( ! is_array( $plugins ) ) {
$plugins = array( $plugins );
}
$errors = array();
foreach ( $plugins as $plugin ) {
if ( ! empty( $redirect ) ) {
$redirect = add_query_arg( 'plugin', $plugin, $redirect );
}
$result = activate_plugin( $plugin, $redirect, $network_wide, $silent );
if ( is_wp_error( $result ) ) {
$errors[ $plugin ] = $result;
}
}
if ( ! empty( $errors ) ) {
return new WP_Error( 'plugins_invalid', __( 'One of the plugins is invalid.' ), $errors );
}
return true;
}注意事项
- 返回 WP_Error 时,表示至少一个插件文件路径无效或激活过程中出错,而非插件本身有功能错误。
- 使用 $silent 参数可避免触发插件的激活钩子,适用于需要静默激活的场景。
- 函数自 WordPress 2.6.0 版本引入,相关函数包括 activate_plugin()、__()、add_query_arg()、is_wp_error() 和 WP_Error::__construct()。
原文内容
Activates multiple plugins.
Description
When WP_Error is returned, it does not mean that one of the plugins had errors. It means that one or more of the plugin file paths were invalid.
The execution will be halted as soon as one of the plugins has an error.
Parameters
$pluginsstring|string[]required-
Single plugin or list of plugins to activate.
$redirectstringrequired-
Redirect to page after successful activation.
$network_widebooloptional-
Whether to enable the plugin for all sites in the network.
Default:
false $silentbooloptional-
Prevent calling activation hooks.
Default:
false
Source
function activate_plugins( $plugins, $redirect = '', $network_wide = false, $silent = false ) {
if ( ! is_array( $plugins ) ) {
$plugins = array( $plugins );
}
$errors = array();
foreach ( $plugins as $plugin ) {
if ( ! empty( $redirect ) ) {
$redirect = add_query_arg( 'plugin', $plugin, $redirect );
}
$result = activate_plugin( $plugin, $redirect, $network_wide, $silent );
if ( is_wp_error( $result ) ) {
$errors[ $plugin ] = $result;
}
}
if ( ! empty( $errors ) ) {
return new WP_Error( 'plugins_invalid', __( 'One of the plugins is invalid.' ), $errors );
}
return true;
}
Changelog
| Version | Description |
|---|---|
| 2.6.0 | Introduced. |