(总结)重排文章与评论ID

20141118:当前博主使用的WP版本在wp-config.php中关掉Revision后依旧会在修改旧文章时出现由于Autosave导致的Rev,这部分需要手动删除。

本文适用于受不了ID跳号的重度强迫症患者,用以将文章和评论的ID完全从1开始排序。

警告:重排文章ID会导致搜索引擎索引完全失效,下面虽然会介绍一个跳转方法,但依旧非常不建议进行这个操作!

重排文章ID:

create table post_map(id int auto_increment primary key, oldid int unique key);
insert into post_map(oldid) select id from wp_posts order by id asc;
update wp_posts set id = (select id from post_map where oldid = id);
update wp_comments set comment_post_id = (select id from post_map where oldid = comment_post_id);
update wp_postmeta set post_id = (select id from post_map where oldid = post_id);
update wp_term_relatioships set object_id = (select id from post_map where oldid = object_id) where term_taxonomy_id in (select term_taxonomy_id from wp_term_taxonomy where taxonomy != 'link_category');

评论重排:

create table comment_map (id int auto_increment primary key, oldid int unique key);
insert into comment_map (oldid) select comment_id from wp_comments order by comment_id asc;
update wp_comments set comment_id = (select id from comment_map where oldid = comment_id);
update wp_comments set comment_parent = (select id from comment_map where oldid = comment_parent) where exists (select id from comment_map where oldid = comment_parent);
update wp_commentmeta set comment_id = (select id from comment_map where oldid = comment_id) where exists (select id from comment_map where oldid = comment_parent);

对于搜索引擎的失效,可以在旧ID有、新ID没有的情况下做跳转,但对于新旧不同的只好任由文不对题,可以在文章里加行字“如果你发现文章不对,点击访问新地址”,由读者判断。附当时的博主的一段代码参考:

<?php
mysql_connect('localhost', '********', '********');
mysql_select_db('wordpress');
if (defined('WP_USE_THEMES'))
{
    if (preg_match('/^\/(\d+)$/', $_SERVER['HTTP_X_REWRITE_URL'], $matches))
    {
        $p = $matches[1];
        $result = mysql_query('select ID from wp_posts where ID = ' . $p);
        if (mysql_num_rows($result) == 0)
        {
            header('Location: http://lxf.me/old.php?p=' . $p, true, 301);
            exit();
        }
    }
}
else
{
    $p = $_GET['p'];
    $result = mysql_query('select id from post_map where oldid = ' . $p);
    $row = mysql_fetch_assoc($result);
    header('Location: http://lxf.me/' . $row['id'], true, 301);
    mysql_free_result($result);
}
mysql_close();

Leave a Reply

Your email address will not be published. Required fields are marked *

Using REAL email address will help you receive reply notifications.