dead_db()
云策文档标注
概述
dead_db() 函数用于处理数据库连接错误,优先加载自定义错误模板,否则显示 WordPress 默认错误。它设置 HTTP 状态码为 500 以防止搜索引擎缓存错误信息。
关键要点
- 如果 wp-content 目录中存在 db-error.php 文件,则加载该自定义错误页面并终止执行。
- 否则,根据安装或管理状态显示详细或简略的 WordPress 数据库错误信息。
- 此函数从 WordPress 2.5.0 引入,并向后移植到 2.3.2 版本。
代码示例
function dead_db() {
global $wpdb;
wp_load_translations_early();
// Load custom DB error template, if present.
if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
require_once WP_CONTENT_DIR . '/db-error.php';
die();
}
// If installing or in the admin, provide the verbose message.
if ( wp_installing() || defined( 'WP_ADMIN' ) ) {
wp_die( $wpdb->error );
}
// Otherwise, be terse.
wp_die( '' . __( 'Error establishing a database connection' ) . '', __( 'Database Error' ) );
}注意事项
- 自定义 db-error.php 文件应同样设置 HTTP 状态码为 500,以保持一致性。
- 函数在安装模式或管理后台中会显示详细的数据库错误信息,否则显示简略错误。
原文内容
Loads custom DB error or display WordPress DB error.
Description
If a file exists in the wp-content directory named db-error.php, then it will be loaded instead of displaying the WordPress DB error. If it is not found, then the WordPress DB error will be displayed instead.
The WordPress DB error sets the HTTP status header to 500 to try to prevent search engines from caching the message. Custom DB messages should do the same.
This function was backported to WordPress 2.3.2, but originally was added in WordPress 2.5.0.
Source
function dead_db() {
global $wpdb;
wp_load_translations_early();
// Load custom DB error template, if present.
if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
require_once WP_CONTENT_DIR . '/db-error.php';
die();
}
// If installing or in the admin, provide the verbose message.
if ( wp_installing() || defined( 'WP_ADMIN' ) ) {
wp_die( $wpdb->error );
}
// Otherwise, be terse.
wp_die( '<h1>' . __( 'Error establishing a database connection' ) . '</h1>', __( 'Database Error' ) );
}
Changelog
| Version | Description |
|---|---|
| 2.3.2 | Introduced. |