wp_update_term not creating new unique slug

I think you are running into trouble with these lines in wp_update_term():

3287          // Merge old and new args with new args overwriting old ones.
3288          $args = array_merge($term, $args);

https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/taxonomy.php#L3287

The array passed in gets merged with the data already in the DB.

Set your slug explicitly:

$nname="my new name";
wp_update_term(
  10, 
  'artists', 
  array(
    'name' => $nname,
    'slug' => sanitize_title($nname)
  )
);   

sanitize_title() is the same function used by wp_update_term() to convert the name to a slug:

3309          $empty_slug = false;
3310          if ( empty( $args['slug'] ) ) {
3311                  $empty_slug = true;
3312                  $slug = sanitize_title($name);
3313          } else {
3314                  $slug = $args['slug'];
3315          }

https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/taxonomy.php#L3312

That won’t automatically prevent duplicate terms though. The wp_insert_term() function uses wp_unique_term_slug() instead.

2844          $slug = wp_unique_term_slug( $slug, (object) $args );

https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/taxonomy.php#L2844

So using that in lieu of sanitize_title() in the code above should do the trick.

Leave a Comment