custom slug always ends in “-2”

I have a custom post type called task. I want the slug of each task to be an id, rather than use the entered title. I’ve modified the code from this SO question “How to customize this automatic slug shortener with an overrwrite function” as such:

add_filter('name_save_pre', array(__CLASS__, 'change_task_slug_to_id'));
static function change_task_slug_to_id($slug)
{
    // should prevent slug from being continually modified
    if ($slug) return $slug;
    return date('U');
}

However every time I add a new task, the slug is created with “-2” appended to it:
enter image description here

How can I prevent WordPress from re-modifying the slug, and appending the “-2”?

1 Answer
1

Modification of a slug happens when wordpress detect that the slug is already in use. “In use” in this case includes the posts that are trashed. In your case if you don’t need the id to be associated with the date then you might get better result by using the post id as the id, or implement some incremental counter.

Update:
There was actually a ticket specific to numeric slugs https://core.trac.wordpress.org/ticket/5305. Should be fixed in 4.4

And it eems like there is a collusion detection with date (year) urls.

Leave a Comment