Skip to main content
Login Join
Snippet · PHP

Prevent Duplicate Post Titles in WordPress

Shared by Naman Chauhan · June 4, 2026

13 views
3 upvotes
Back to Snippets

Prevent users from publishing or updating a post if another post with the same title already exists. This helps avoid duplicate articles, pages, and SEO issues.

/**
 * Prevent duplicate post titles.
 */

add_filter( 'wp_insert_post_data', 'wpfolks_prevent_duplicate_titles', 10, 2 );

function wpfolks_prevent_duplicate_titles( $data, $postarr ) {

	// Skip auto drafts and revisions.
	if (
		in_array(
			$data['post_status'],
			array( 'auto-draft', 'inherit' ),
			true
		)
	) {
		return $data;
	}

	global $wpdb;

	$existing_post = $wpdb->get_var(
		$wpdb->prepare(
			"
			SELECT ID
			FROM {$wpdb->posts}
			WHERE post_title = %s
			AND post_type = %s
			AND ID != %d
			LIMIT 1
			",
			$data['post_title'],
			$data['post_type'],
			$postarr['ID'] ?? 0
		)
	);

	if ( $existing_post ) {

		wp_die(
			__( 'A post with this title already exists. Please choose a different title.', 'textdomain' ),
			__( 'Duplicate Title Detected', 'textdomain' ),
			array(
				'back_link' => true,
			)
		);
	}

	return $data;
}
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