From what I can tell, wp_insert_post will automatically append a -# to your post slug. So why does wp_unique_post_slug exist?

Is it just there for legacy purposes or is there still a good reason to use it?

  • if you scroll down in in the source code of wp_insert_post() developer.wordpress.org/reference/functions/wp_insert_post/… to line 3679, you will see that that function actually calls wp_unique_post_slug() ... – Michael May 21 '19 at 3:43
  • 2
    It exists because it's the one which automatically adds that -# (i.e. number suffix) to the post slug when there's an existing post with the same slug without the suffix. So the function exists and being called from wp_insert_post() to make sure the slug is unique - just as the function name implies. – Sally CJ May 21 '19 at 4:01

As the commenters have noticed wp_unique_post_slug is called from wp_insert_post to ensure there are no double slugs. It is also called from two other functions, which explains why it is a separate function and not incorporated in wp_insert_post.

A little used feature is the possibility to apply filters present in wp_unique_post_slug. There are two of them:

  1. pre_wp_unique_post_slug allows you to completely bypass the unique post slug generation, for instance if you want to use a completely different slug for your posts (say, based on some metafield in stead of the title).
  2. wp_unique_post_slug allows you to change the unique post slug that has been generated, for instance if you dislike the number-suffix and want to replace it with something else or if you want to prepend every slug with the post tag or so.

So, apart from the obvious fact that wp_unique_post_slug is an essential WP function, there are also advanced uses. 

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.