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
- …
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0