Fredy31
Fredy31

Reputation: 2817

WordPress how to hook onto slug generator

I'd like to change the slug that is automatically generated when creating a post.

enter image description here

I'd like to add a meta before, making a thing like [meta]-test-slug-2

I guess there's a hook on when WordPress automatically creates a slug, and if I could find it, I could inject that meta before the title when creating the slug.

So is there a hook that exists? If so, how can I use it?

Upvotes: 1

Views: 1898

Answers (2)

Sergey Sklyar
Sergey Sklyar

Reputation: 1970

Change $prefix variable to fit your needs:

add_filter( 'wp_unique_post_slug', 'prefix_wp_unique_post_slug', 2, 6 );
function prefix_wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
    if ( $post_type == 'post' ) {

        $prefix = 'meta-';
        if ( strripos($slug, $prefix) !== 0 ) {
            $slug = $prefix . $slug;
        }
    }
    return $slug;
}

Upvotes: 2

Kallmanation
Kallmanation

Reputation: 1182

See the answer to this question.

In short the filter wp_unique_post_slug will allow you to modify the slug.

But it seems that is called with every save of the post, so I would recommend some logic to only prefix on the first save, so users can edit the slug as they like.

Upvotes: 0

Related Questions