Skip to content

Instantly share code, notes, and snippets.

@seoave
Created July 20, 2024 15:21
Show Gist options
  • Save seoave/767136b4e845637b792a0b19ac987bed to your computer and use it in GitHub Desktop.
Save seoave/767136b4e845637b792a0b19ac987bed to your computer and use it in GitHub Desktop.
Prevent duplicate WP custom CPT post slugs. This will append the string '-duplicate' to the end of any duplicate slugs. This code cannot prevent duplicate slugs if they already exist prior to implementing this solution. Be sure to check for duplicates first.
function prevent_slug_duplicates( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
$check_post_types = array(
'post',
'page',
'custom_post_type'
);
if ( ! in_array( $post_type, $check_post_types ) ) {
return $slug;
}
if ( 'custom_post_type' == $post_type ) {
// Saving a custom_post_type post, check for duplicates in POST or PAGE post types
$post_match = get_page_by_path( $slug, 'OBJECT', 'post' );
$page_match = get_page_by_path( $slug, 'OBJECT', 'page' );
if ( $post_match || $page_match ) {
$slug .= '-duplicate';
}
} else {
// Saving a POST or PAGE, check for duplicates in custom_post_type post type
$custom_post_type_match = get_page_by_path( $slug, 'OBJECT', 'custom_post_type' );
if ( $custom_post_type_match ) {
$slug .= '-duplicate';
}
}
return $slug;
}
add_filter( 'wp_unique_post_slug', 'prevent_slug_duplicates', 10, 6 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment