How to prevent duplicate slugs for wp_insert_post?

If you use wp_insert_post, it should calculate a unique post slug for you. If you don’t use wp_insert_post, try using wp_unique_post_slug. If neither of those are working for you, you could simple try appending -page or to the new page’s post_name (slug) before inserting it.

WordPress does its uniqueness check on post slugs at application level — it doesn’t look like there’s a unique index on wp_posts.post_name. So, for instance, if you’re inside a transaction where you’re creating two posts simultaneously, the uniqueness checks would fail. It’s also possible that you could create some sort of race condition where the two posts are being inserted at the same time and a uniqueness check on both slugs would fail.

Leave a Comment