MySQL查询删除重复的WordPress帖子?

时间:2013-06-10 作者:Nguyen

我有很多重复的帖子。那么,如何删除它们(只保留1篇帖子)。如果标题相同,则为重复帖子。非常感谢!祝你今天愉快!

2 个回复
最合适的回答,由SO网友:Bendoh 整理而成

我不完全确定MySQL中的单个查询是否可以做到这一点,因为您无法从子查询中引用的表中删除。实际上,我建议使用wp-cli 并使用WordPress API删除重复的帖子(这也将删除任何帖子元和相关术语参考):

global $wpdb;

$duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} GROUP BY post_title HAVING COUNT(*) > 1");

foreach( $duplicate_titles as $title ) {
   $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) ); 
   // Iterate over the second ID with this post title till the last
   foreach( array_slice( $post_ids, 1 ) as $post_id ) {
       wp_delete_post( $post_id, true ); // Force delete this post
   }
}
希望这有帮助。

SO网友:Julian Hi

我知道,这是一个老帖子,但由于我有一个类似的问题,我想在Bendoh的回答中添加一些建议(不幸的是,我没有发表评论的名声)

由于wordpress和一些插件也在post表中存储数据,我建议在您的查询中添加post\\u类型:

global $wpdb;

$duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} WHERE `post_type` = \'post\' GROUP BY post_title HAVING COUNT(*) > 1");

foreach( $duplicate_titles as $title ) {
    $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) ); 
    // Iterate over the second ID with this post title till the last
    foreach( array_slice( $post_ids, 1 ) as $post_id ) {
        wp_delete_post( $post_id, true ); // Force delete this post
    }
}
根据副本的来源,我还会添加另一个字段来检查副本,如发布日期。

global $wpdb;

$duplicate_titles = $wpdb->get_results("SELECT post_title, post_date, CONCAT(post_date, post_title) AS WHOLENAME FROM {$wpdb->posts} WHERE post_type = \'post\' GROUP BY WHOLENAME HAVING COUNT(WHOLENAME) > 1");


foreach( $duplicate_titles as $title ) {

    $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s AND post_date=\'".$title->post_date."\'", $title->post_title ) ); 

    foreach( array_slice( $post_ids, 1 ) as $post_id ) {
        wp_delete_post( $post_id, true ); // Force delete this post
    }

}

结束

相关推荐