WordPress – How to Prevent Duplicate Post Titles

If you have a lot of people contributing content to your blog, you might accidentally have two posts with the same title. By default, WordPress doesn’t raise any red flags when that happens. It’ll generate a unique URL by appending a number (1, 2, etc.) after the original URL and so prevent any conflict. But it’s a terrible idea to have duplicate titles like this. Not only will they contend with each other, they might both be devalued!

While there are several plugins that prevent duplicate titles from being added, I’ll show you how to ban duplicate post titles without plugins.

Disallow Duplicate Post Titles – Add Code

In your functions.php or wherever you place your custom PHP code, add the following:

function disallow_posts_with_same_title($messages) {
    global $post;
    global $wpdb ;
    $title = $post->post_title;
    $post_id = $post->ID ;
    $wtitlequery = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_title = '{$title}' AND ID != {$post_id} " ;
 
    $wresults = $wpdb->get_results( $wtitlequery) ;
 
    if ( $wresults ) {
        $error_message = 'This title is already used. Please choose another';
        add_settings_error('post_has_links', '', $error_message, 'error');
        settings_errors( 'post_has_links' );
        $post->post_status = 'draft';
        wp_update_post($post);
        return;
    }
    return $messages;

}
add_action('post_updated_messages', 'disallow_posts_with_same_title');

If you don’t know how to add code to your functions.php, read the following earlier tutorial on adding code snippets to WordPress.

This code works in a very simple manner. It provides an action hook that fires whenever the post is updated – either saved as a draft, pending, or published. Then it runs an SQL query against the WordPress database searching for similar titles but with a different Post ID compared to the current one. If any results are returned, we know that it’s a duplicate post title.

We display the error message in the post editor using the graceful message framework provided by WordPress:

Duplicate Post Titles Error Message

This is a great way to inform authors that something is wrong with their post. Instead of an unfriendly error message that leads them to a blank page, we display it right at the top of the post and revert the post to a “draft” status, thus preventing it from being published.

So there’s no need for a separate WordPress plugin to prevent duplicate post titles on your WordPress website. Simply add the above code and you’re done!

Speak Your Mind

*