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
- Open your active theme’s
functions.phpfile or a custom functionality plugin. - Add the code below.
- Save the file.
- Try publishing a post with a title that already exists. WordPress will display an error message.
Benefits
- Prevents duplicate post titles.
- Keeps content organized.
- Reduces editor mistakes.
- Works for all post types.
- Lightweight solution without additional plugins.
/**
* 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 );