众所周知,wordpress这款强大的免费系统,不论是已经发布的文章,还是上传的图片,还是缓存的文章,都占用1个ID数字号,这就导致了没有几篇文章,却有很多ID数字号的问题。用下面的这段代码,可以大幅度的清理掉没有用的ID数字号并给文章重新排序生成新的ID号。

$wpdb->query('update ' . $wpdb->prefix . 'term_relationships set object_id = ' . $convertedrows . ' where object_id = ' . $id);
$wpdb->query('update ' . $wpdb->prefix . 'postmeta set post_id = ' . $convertedrows . ' where post_id = ' . $id);
$wpdb->query('update ' . $wpdb->prefix . 'comments set comment_post_ID = ' . $convertedrows . ' where comment_post_ID = ' . $id);
$convertedrows++;
}
/** ID默认由1开始 */
$convertedrows = 1;
/** 库文章表所有记录 */
$sql_query = 'SELECT ID FROM ' . $table_prefix . 'posts ORDER BY ID ASC';
$all_post_ids = $wpdb->get_results($sql_query);
/** 有返回值时则执行循环 */
if (is_array($all_post_ids)) {
foreach ($all_post_ids as $post_id) {
change_post_id($post_id->ID);
}
}
/** 重新设置文章ID自动增加的起点 */
$wpdb->query('alter table ' . $table_prefix . 'posts AUTO_INCREMENT = ' . $convertedrows);
echo 'Total:' . $convertedrows . ', It\'s ok! ';
?>

保存的wordpress安装目录下面,运行即可。

发表回复