wp_set_wpdb_vars()
云策文档标注
概述
wp_set_wpdb_vars() 函数用于设置数据库表前缀和表列的格式说明符。它初始化 $wpdb->field_types 数组,定义特定列的格式(如 %d 表示整数),并处理表前缀设置错误。
关键要点
- 设置数据库表前缀和列格式说明符,未列出的列默认使用 %s。
- 初始化 $wpdb->field_types 数组,包含多个 WordPress 核心表的整数列(如 post_author、term_id、user_id 等)。
- 调用 $wpdb->set_prefix() 设置表前缀,若出错则加载翻译并终止执行。
- 函数在 WordPress 3.0.0 版本引入,用于数据库连接初始化阶段。
代码示例
function wp_set_wpdb_vars() {
global $wpdb, $table_prefix;
if ( ! empty( $wpdb->error ) ) {
dead_db();
}
$wpdb->field_types = array(
'post_author' => '%d',
'post_parent' => '%d',
'menu_order' => '%d',
'term_id' => '%d',
'term_group' => '%d',
'term_taxonomy_id' => '%d',
'parent' => '%d',
'count' => '%d',
'object_id' => '%d',
'term_order' => '%d',
'ID' => '%d',
'comment_ID' => '%d',
'comment_post_ID' => '%d',
'comment_parent' => '%d',
'user_id' => '%d',
'link_id' => '%d',
'link_owner' => '%d',
'link_rating' => '%d',
'option_id' => '%d',
'blog_id' => '%d',
'meta_id' => '%d',
'post_id' => '%d',
'user_status' => '%d',
'umeta_id' => '%d',
'comment_karma' => '%d',
'comment_count' => '%d',
// Multisite:
'active' => '%d',
'cat_id' => '%d',
'deleted' => '%d',
'lang_id' => '%d',
'mature' => '%d',
'public' => '%d',
'site_id' => '%d',
'spam' => '%d',
);
$prefix = $wpdb->set_prefix( $table_prefix );
if ( is_wp_error( $prefix ) ) {
wp_load_translations_early();
wp_die(
sprintf(
__( 'Error: %1$s in %2$s can only contain numbers, letters, and underscores.' ),
'$table_prefix',
'wp-config.php'
)
);
}
}注意事项
- 函数在数据库连接错误时调用 dead_db() 处理错误。
- 表前缀设置失败会触发 wp_die() 显示错误消息,确保配置正确性。
- 适用于 WordPress 核心开发,通常不需要直接调用。
原文内容
Sets the database table prefix and the format specifiers for database table columns.
Description
Columns not listed here default to %s.
Source
function wp_set_wpdb_vars() {
global $wpdb, $table_prefix;
if ( ! empty( $wpdb->error ) ) {
dead_db();
}
$wpdb->field_types = array(
'post_author' => '%d',
'post_parent' => '%d',
'menu_order' => '%d',
'term_id' => '%d',
'term_group' => '%d',
'term_taxonomy_id' => '%d',
'parent' => '%d',
'count' => '%d',
'object_id' => '%d',
'term_order' => '%d',
'ID' => '%d',
'comment_ID' => '%d',
'comment_post_ID' => '%d',
'comment_parent' => '%d',
'user_id' => '%d',
'link_id' => '%d',
'link_owner' => '%d',
'link_rating' => '%d',
'option_id' => '%d',
'blog_id' => '%d',
'meta_id' => '%d',
'post_id' => '%d',
'user_status' => '%d',
'umeta_id' => '%d',
'comment_karma' => '%d',
'comment_count' => '%d',
// Multisite:
'active' => '%d',
'cat_id' => '%d',
'deleted' => '%d',
'lang_id' => '%d',
'mature' => '%d',
'public' => '%d',
'site_id' => '%d',
'spam' => '%d',
);
$prefix = $wpdb->set_prefix( $table_prefix );
if ( is_wp_error( $prefix ) ) {
wp_load_translations_early();
wp_die(
sprintf(
/* translators: 1: $table_prefix, 2: wp-config.php */
__( '<strong>Error:</strong> %1$s in %2$s can only contain numbers, letters, and underscores.' ),
'<code>$table_prefix</code>',
'<code>wp-config.php</code>'
)
);
}
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |