wp_upgrade()
云策文档标注
概述
wp_upgrade() 函数用于在 WordPress 站点更新时执行数据库升级流程。它检查数据库版本,并在需要时调用一系列升级函数来更新数据库结构和数据。
关键要点
- 函数核心功能是升级数据库,仅在当前数据库版本与目标版本不一致时执行。
- 执行前会检查站点是否已安装,并验证 MySQL 版本。
- 升级过程包括刷新缓存、预升级处理、静默更新数据库、执行所有升级例程,并在多站点环境中处理网络升级。
- 升级完成后会更新站点元数据、删除相关瞬态,并触发 wp_upgrade 钩子。
代码示例
function wp_upgrade() {
global $wp_current_db_version, $wp_db_version;
$wp_current_db_version = (int) __get_option( 'db_version' );
// We are up to date. Nothing to do.
if ( $wp_db_version === $wp_current_db_version ) {
return;
}
if ( ! is_blog_installed() ) {
return;
}
wp_check_mysql_version();
wp_cache_flush();
pre_schema_upgrade();
make_db_current_silent();
upgrade_all();
if ( is_multisite() && is_main_site() ) {
upgrade_network();
}
wp_cache_flush();
if ( is_multisite() ) {
update_site_meta( get_current_blog_id(), 'db_version', $wp_db_version );
update_site_meta( get_current_blog_id(), 'db_last_updated', microtime() );
}
delete_transient( 'wp_core_block_css_files' );
do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
}注意事项
- 函数在数据库版本已最新或站点未安装时会提前返回,避免不必要的操作。
- 多站点环境下,仅主站点会执行网络升级,并更新站点特定的元数据。
- 升级后触发 wp_upgrade 钩子,允许开发者添加自定义操作。
原文内容
Runs WordPress Upgrade functions.
Description
Upgrades the database if needed during a site update.
Source
function wp_upgrade() {
global $wp_current_db_version, $wp_db_version;
$wp_current_db_version = (int) __get_option( 'db_version' );
// We are up to date. Nothing to do.
if ( $wp_db_version === $wp_current_db_version ) {
return;
}
if ( ! is_blog_installed() ) {
return;
}
wp_check_mysql_version();
wp_cache_flush();
pre_schema_upgrade();
make_db_current_silent();
upgrade_all();
if ( is_multisite() && is_main_site() ) {
upgrade_network();
}
wp_cache_flush();
if ( is_multisite() ) {
update_site_meta( get_current_blog_id(), 'db_version', $wp_db_version );
update_site_meta( get_current_blog_id(), 'db_last_updated', microtime() );
}
delete_transient( 'wp_core_block_css_files' );
/**
* Fires after a site is fully upgraded.
*
* @since 3.9.0
*
* @param int $wp_db_version The new $wp_db_version.
* @param int $wp_current_db_version The old (current) $wp_db_version.
*/
do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
}
Hooks
- do_action( ‘wp_upgrade’, int $wp_db_version, int $wp_current_db_version )
-
Fires after a site is fully upgraded.
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |