Hey, chucked together a one function plugin to try and achieve what you wanted:
<?php
/*
Plugin Name: Overwrite WordPress Posts if Title Already Used
Description: Checks to see if post title has already been used and if so deletes the old post and creates a new one with the given data.
Author: JPG
Version: 1.0
*/
// Filter used to access data before it is written to the database
add_filter( 'wp_insert_post_data', 'overwrite_wordpress_post_if_title_exists', 99, 2 );
// Our function to delete the old post if there is a title clash (title must be identical)
function overwrite_wordpress_post_if_title_exists( $data, $postarr ) {
// Return if we aren't saving/updating a post
if ( $data['post_status'] !== 'publish' ) {
return $data;
}
// Return all existing posts
$posts = get_posts( array( 'post_type' => 'post' ) );
// Loop through exisiting posts
foreach ( $posts as $post ) {
// If title already exists, delete the old post before we save the new one (change 'false' to 'true' to delete the post rather than trash it)
if ( get_the_title( $post ) == $data['post_title'] && $post->ID != $postarr['ID'] ) {
wp_delete_post( $post->ID, false );
$data['post_name'] = sanitize_title( $data['post_title'] );
}
}
return $data;
}
?>
Not tested excessively but figured it gives you a starting point if this looks like it is close to what you wanted. Be aware it currently makes adjustments when you are publishing a post (if status is anything other it won’t do anything).
Also, as the note says with wp_delete_post set to false exisiting posts will get trashed NOT deleted permanently (figured this was safer in case you want to recover an old post).
This does, however, mess with your permalinks a tad in that in the post edit screen you will see the ‘wordpress-rules-2’ as before but when you are on the frontend and viewing the post it should use the desired url: ‘wordpress-rules’.
Be sure to test it fully with dummy data before you go deleting anything important ??
Hope this helps a tad!