Is it possible to add default prefix to the slug of each newly added Tag. So that full slug, would be stored in database (no rewrites). For example:

  • Name: Tag1 -> Slug: prefix-tag1
  • Name: Tag2 -> Slug: prefix-tag2
  • ...
link|improve this question
feedback

1 Answer

up vote 1 down vote accepted

You can use the created_term or the created_{taxonomy} hooks which are fired just after a taxonomy term is created (the second only if it matches the taxonomy).

The following will only alter terms in the taxonomy 'my-taxonomy'. (I believe for the default tags, taxonomy should be 'post_tag').

add_action('created_term', 'my_add_prefix_to_term', 10, 3);
function my_add_prefix_to_term( $term_id,$tt_id,$taxonomy ) {
    if( $taxonomy == 'my-taxonomy'){
        $term = get_term( $term_id, $taxonomy );
        $args = array('slug'=>'my-prefix-'.$term->slug);
        wp_update_term( $term_id,$taxonomy, $args );
    }
}

Note: From the Codex:

It should also be noted that if you set 'slug' and it isn't unique then a WP_Error will be passed back

This shouldn't be a problem if you use this function before any terms are created, because prefixing the same string to unique slugs preserves uniquness.

link|improve this answer
Updated: I don't know why, but it didn't work from the first time. But after playing with code, and going back to the your version, now it works fine. I didn't succeed with created_{taxonomy} -> created_post_tag, but with created_term works fine. I use it with 'post_tag' and custom taxonomy too. Thank you Stephen! You saved me a lot of time, I was trying to find the solution for the half a day. – Andrew Feb 16 at 17:03
feedback

Your Answer

 
or
required, but never shown

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