This weekend I’ve learned something new about WordPress and this is really specific topic and there is no more answers. So I wanted to share my solution;
Problem: WordPress migrations (especially migration from another platform) gives pain and generally migration issues or latency problems adding duplicated records to database. And here we go!
If you have more than one content has same post type and same post_name, you’ll get 404 error! Because post_name field is used to provide WordPress the permalink for the post.
WordPress’s post_name filed that in posts table shouldn’t be unique? What!
I can't find any reasonable answer. Why post_name field isn't set as unique? cc @nacin
— Mustafa Uysal (@m_uysl) November 9, 2013
Yes I’ve asked and got my answer (thanks @nacin) , and now making sense.
This is meaningful? Ok, but it’s not fixing our problem.
Solution?
Create a new php file on the WordPress root.
Ex: fix-duplicated-posts.php
and insert these code
[code language=”php”]
<?php
require( ‘wp-load.php’ );
//set_time_limit(30000); // you can set time limit, but I prefer to use command line > php fix-duplicated-posts.php
$query = "SELECT id,post_name, Count(*) FROM wp_posts WHERE post_type = ‘post’ GROUP BY post_name HAVING Count(*) > 1";
$duplicated_posts = $wpdb->get_results( $query );
foreach ( $duplicated_posts as $result ) {
$prepost = get_post($result->id);
$prepost->post_name = ”;
wp_update_post( $prepost );
}
[/code]
and run it 🙂 That’s all!
Note: I’ve used this for content-heavy website, so I run php via command line ( php fix-duplicated-posts.php). If you have thousands content in the posts table (I’ve tested with a website that has ~500k posts row and ~70k real content) you can set time or better way use command-line 😉
Tip: This script will fix one post each run, so maybe you want to run it a few times, don’t forget to check database.