i have two post duplicate Post Titles: "Love Story".
i want code Automatically add a random words if Duplicate Post Titles, like post 2 duplicate Titles ==> auto change post 2 titles like: "Love Story Two".
and if user up post 3, duplicate Titles again => auto add random words in post titles like : "Love story three".
thanks a lot
i have two post duplicate Post Titles: "Love Story".
i want code Automatically add a random words if Duplicate Post Titles, like post 2 duplicate Titles ==> auto change post 2 titles like: "Love Story Two".
and if user up post 3, duplicate Titles again => auto add random words in post titles like : "Love story three".
thanks a lot
Please give this a shot. I didn't test it, so let me know if it has any errors. Basically, it will check the title before saving and run a loop checking to see if it can get a post by that title. If it can, it will add a new suffix and keep trying.
As you can see, you'll have to add more number to the $suffixes
array to allow it go count farther. Alternatively, you could use The NumberFormatter
class if available.
add_filter( 'wp_insert_post_data' , 'filter_post_title' , '99', 2 );
function filter_post_title( $data , $postarr ) {
if( !$postarr['ID'] ) { // Publishing for the first time
$suffixes = array( 'Two', 'Three', 'Four' );
$count = 0;
$original_title = $data['post_title'];
$new_title = $original_title;
while( get_page_by_title( $new_title, 'object', 'post' ) ) {
$new_title = $original_title . " " . $suffixes[$count];
$count++;
}
$data['post_title'] = $new_title;
}
return $data;
}
You could write it with fewer variables, but I feel this way is more readable.
Edit: The downside to this is that it has to query the database each time it increments. So, to get to "Five" it would require five queries. If you start having it count to high numbers you will start to notice the saving process taking longer. In that case, querying all the posts that start with the current title and then parsing them to find the current number would be more efficient.