add_clean_index()
云策文档标注
概述
add_clean_index() 函数用于向指定数据库表添加索引,以优化查询性能。它先删除现有同名索引,再创建新索引,确保索引的清洁性。
关键要点
- 函数接受两个必需参数:$table(表名)和 $index(索引列名)。
- 内部调用 drop_index() 删除旧索引,然后使用 $wpdb->query() 执行 ALTER TABLE 语句添加索引。
- 返回 true 表示执行完成,适用于数据库升级或性能优化场景。
代码示例
function wpdocs_mwb_make_fetch_fast() {
global $wpdb;
// 添加清理索引
add_clean_index( $wpdb->posts, 'post_name' );
add_clean_index( $wpdb->categories, 'category_nicename' );
add_clean_index( $wpdb->comments, 'comment_approved' );
add_clean_index( $wpdb->posts, 'post_status' );
}
原文内容
Adds an index to a specified table.
Parameters
$tablestringrequired-
Database table name.
$indexstringrequired-
Database table index column.
Source
function add_clean_index( $table, $index ) {
global $wpdb;
drop_index( $table, $index );
$wpdb->query( "ALTER TABLE `$table` ADD INDEX ( `$index` )" );
return true;
}
Changelog
| Version | Description |
|---|---|
| 1.0.1 | Introduced. |
Skip to note 2 content
MakeWebBetter
Sometimes after a table has been created in a database, we find that it is advantageous to add an index to that table to speed up queries involving this table.
function wpdocs_mwb_make_fetch_fast() { global $wpdb; // Add some Clean up indices add_clean_index( $wpdb->posts, 'post_name' ); add_clean_index( $wpdb->categories, 'category_nicename' ); add_clean_index( $wpdb->comments, 'comment_approved' ); add_clean_index( $wpdb->posts, 'post_status' ); }