Wordpress数据表里包含很多的数据信息。例如:文章、评论、标签、分类等。也有许多多余的信息,例如:文章自动草稿、文章修订信息、更换主题产生的多余数据表、删除插件多余的插件配置。这些多余的信息会随着文章的数量、更换的主题、删除的插件数量的叠加会越来越多。造成的结果就是网站速度越来越慢。

那么怎么清理呢?当然清理之前要备份好。

1)、清除wordpress中的基本配置(wp_options表)

造成wp_options数据 多余的主要途径有两个,一是频繁的安装卸载插件。二是大量的RSS缓存。清理的方法,首先在根目录下wp_config.php文件中加入define('MAGPIE_CACHE_ON', '0');代码来阻止RSS缓存的生成。其次是使用如下代码:

DELETE FROM wp_options WHERE option_name LIKE ('%_transient_%');
DELETE FROM wp_options WHERE option_name REGEXP '_transient_';

删除RSS缓存数据。

2)、清理wp_posts表

Wp_posts表多余的数据主要是修订版和自动草稿。使用如下代码删除未发布的文章、页面、导航。

DELETE FROM wp_posts WHERE NOT(post_status = 'publish' AND post_type IN('post','nav_menu_item','page'));

删除全部文章修订版本及所对应的关联数据:

DELETE a,b,c FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id) LEFT JOIN wp_postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision';

删除自动保存草稿以及修订版本的文章

DELETE FROM wp_posts where (post_status='auto-draft' or post_status='inherit') and post_type='post';

3)、清理wp_postmeta 表

wp_postmeta 表数据主要是删除文章表后,关联的无用数据。以及主题和插件关闭后残余数据。

删除文章后关联的数据

DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT post_id FROM wp_posts);

删除_edit_lock和_edit_last条目

DELETE FROM wp_postmeta WHERE meta_key = '_edit_lock';
DELETE FROM wp_postmeta WHERE meta_key = '_edit_last';

删除重复的 meta key 和 value 记录,仅保留最新的一个

DELETE FROM wp_postmeta WHERE meta_id IN (
select * from (select meta_id FROM wp_postmeta pm WHERE
meta_id NOT IN (SELECT max(meta_id) FROM wp_postmeta pm2 where pm2.post_id=pm.post_id and pm2.meta_key=pm.meta_key)
) as g1
)

删除附件记录

DELETE FROM wp_postmeta WHERE meta_key = '_wp_attached_file';
DELETE FROM wp_postmeta WHERE meta_key = '_wp_attachment_metadata';

4)、清理 wp_commentmeta 表

   删除所有垃圾留言(包括待审、垃圾评论、回收站评论)

DELETE FROM wp_comments WHERE comment_approved != '1';

   删除待审评论

    DELETE FROM wp_comments WHERE comment_approved = '0';

   删除垃圾评论

    DELETE FROM wp_comments WHERE comment_approved = 'spam';

   删除回收站评论

    DELETE FROM wp_comments WHERE comment_approved = 'trash';

孤立的关系信息(文章、评论等删除后残留在wp_term_relationships表中的信息)

DELETE FROM wp_term_relationships WHERE term_taxonomy_id=1 AND object_id NOT IN (SELECT id FROM wp_posts);

删除没有的标签(有些文章删除了,但标签还在,WordPress不会自动删除的)

DELETE a,b,c FROM wp_terms AS a
LEFT JOIN wp_term_taxonomy AS c ON a.term_id = c.term_id
LEFT JOIN wp_term_relationships AS b ON b.term_taxonomy_id = c.term_taxonomy_id
WHERE (
c.taxonomy = 'post_tag' AND
c.count = 0
);