resume_theme()
云策文档标注
概述
resume_theme() 函数用于尝试恢复单个已暂停的主题。它通过检查主题的 functions.php 文件是否不再引发致命错误来确保安全恢复,并支持重定向处理。
关键要点
- 函数用于恢复单个主题,参数包括主题名称和可选的重定向 URL。
- 如果提供了重定向 URL 并找到 functions.php 文件,会先测试文件是否引发致命错误,避免错误覆盖重定向。
- 返回值为布尔值或 WP_Error 对象,表示成功、主题未暂停或失败情况。
- 内部使用 wp_paused_themes() 删除暂停记录,并涉及错误处理和重定向机制。
代码示例
function resume_theme( $theme, $redirect = '' ) {
global $wp_stylesheet_path, $wp_template_path;
list( $extension ) = explode( '/', $theme );
if ( ! empty( $redirect ) ) {
$functions_path = '';
if ( str_contains( $wp_stylesheet_path, $extension ) ) {
$functions_path = $wp_stylesheet_path . '/functions.php';
} elseif ( str_contains( $wp_template_path, $extension ) ) {
$functions_path = $wp_template_path . '/functions.php';
}
if ( ! empty( $functions_path ) ) {
wp_redirect(
add_query_arg(
'_error_nonce',
wp_create_nonce( 'theme-resume-error_' . $theme ),
$redirect
)
);
ob_start();
if ( ! defined( 'WP_SANDBOX_SCRAPING' ) ) {
define( 'WP_SANDBOX_SCRAPING', true );
}
include $functions_path;
ob_clean();
}
}
$result = wp_paused_themes()->delete( $extension );
if ( ! $result ) {
return new WP_Error(
'could_not_resume_theme',
__( 'Could not resume the theme.' )
);
}
return true;
}注意事项
- 函数在 WordPress 5.2.0 版本中引入,用于错误保护和主题恢复场景。
- 使用前需确保主题已暂停,否则可能返回 false。
- 涉及全局变量 $wp_stylesheet_path 和 $wp_template_path,需注意路径设置。
原文内容
Tries to resume a single theme.
Description
If a redirect was provided and a functions.php file was found, we first ensure that functions.php file does not throw fatal errors anymore.
The way it works is by setting the redirection to the error before trying to include the file. If the theme fails, then the redirection will not be overwritten with the success message and the theme will not be resumed.
Parameters
$themestringrequired-
Single theme to resume.
$redirectstringoptional-
URL to redirect to. Default empty string.
Source
function resume_theme( $theme, $redirect = '' ) {
global $wp_stylesheet_path, $wp_template_path;
list( $extension ) = explode( '/', $theme );
/*
* We'll override this later if the theme could be resumed without
* creating a fatal error.
*/
if ( ! empty( $redirect ) ) {
$functions_path = '';
if ( str_contains( $wp_stylesheet_path, $extension ) ) {
$functions_path = $wp_stylesheet_path . '/functions.php';
} elseif ( str_contains( $wp_template_path, $extension ) ) {
$functions_path = $wp_template_path . '/functions.php';
}
if ( ! empty( $functions_path ) ) {
wp_redirect(
add_query_arg(
'_error_nonce',
wp_create_nonce( 'theme-resume-error_' . $theme ),
$redirect
)
);
// Load the theme's functions.php to test whether it throws a fatal error.
ob_start();
if ( ! defined( 'WP_SANDBOX_SCRAPING' ) ) {
define( 'WP_SANDBOX_SCRAPING', true );
}
include $functions_path;
ob_clean();
}
}
$result = wp_paused_themes()->delete( $extension );
if ( ! $result ) {
return new WP_Error(
'could_not_resume_theme',
__( 'Could not resume the theme.' )
);
}
return true;
}
Changelog
| Version | Description |
|---|---|
| 5.2.0 | Introduced. |