I have a site with many custom post types and I need a unique slug for each page.
What I’m seeing is that wordpress only checks for slug conflicts within a post type before appending “-2”, “-3”. So I can have “actor/foo”, “book/foo”, “book/foo-2”. I don’t want that. I want each foo to have its own slug no matter the post type.
I want to avoid using a rewrite on the slug and I’d prefer not to edit any WP source outside of plugins/themes.
Is this possible?
A unique slug for posts is done by
wp_unique_post_slug()
. Looking at the source the returned slug is filtered bywp_unique_post_slug
. So we can replace this generated slug with our own.You’ll notice in the source that attachments are required to have unique slugs across all types, so we’ll just use the code from that.
The examples you gave seemed to be non-hierarchal – and it’s not clear if you want the slugs to be unique for hierarchal post types (which by default only need to be unique within their tree) – so in the example below I ignore hierarchal post types.