Automatically add words if duplicate post titles

admin2025-06-03  3

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

Share Improve this question edited Feb 6, 2019 at 19:19 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 6, 2019 at 18:53 Duy HữuDuy Hữu 195 bronze badges 3
  • 1 When should these words be added? When the post is published? – Krzysiek Dróżdż Commented Feb 6, 2019 at 19:18
  • WordPress doesn't care too much about duplication of post titles, it's the slugs that matter. – rudtek Commented Feb 6, 2019 at 21:52
  • @KrzysiekDróżdż yes, When the post is published. – Duy Hữu Commented Feb 6, 2019 at 22:55
Add a comment  | 

1 Answer 1

Reset to default 1

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748925810a314875.html

最新回复(0)