The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Automatically Prevent Duplicate Post Titles

Shared by Amit Dholiya · August 3, 2026 · @wp_insert_post_data

1 copy
47 views
1 upvote
Back to Snippets

Description

This snippet prevents users from publishing or updating a post with a title that already exists for the same post type. It’s especially useful for news sites, documentation websites, product catalogs, and large blogs where duplicate titles can cause confusion.

Steps

  1. Open your active theme’s functions.php file or a custom functionality plugin.
  2. Add the code below.
  3. Save the file.
  4. Try publishing a post with a title that already exists. WordPress will display an error message.

Benefits

/**
 * Prevent duplicate post titles.
 */
function wpfolks_prevent_duplicate_post_titles( $data, $postarr ) {

    if ( empty( $data['post_title'] ) || 'auto-draft' === $data['post_status'] ) {
        return $data;
    }

    global $wpdb;

    $existing = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT ID
             FROM {$wpdb->posts}
             WHERE post_title = %s
             AND post_type = %s
             AND ID != %d
             AND post_status NOT IN ('trash','auto-draft')
             LIMIT 1",
            $data['post_title'],
            $data['post_type'],
            isset( $postarr['ID'] ) ? (int) $postarr['ID'] : 0
        )
    );

    if ( $existing ) {
        wp_die(
            esc_html__( 'A post with this title already exists. Please choose a different title.', 'textdomain' ),
            esc_html__( 'Duplicate Title', 'textdomain' ),
            array( 'response' => 409 )
        );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'wpfolks_prevent_duplicate_post_titles', 10, 2 );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments