0

I want the slug to be recreated every time the term name is updated so it accurately reflects the name.

wp_update_term(10, 'artists', array('name' => 'my new name'));          

The documentation for wp_update_term says:

If the 'slug' argument in $args is missing, then the 'name' in $args will be used. It should also be noted that if you set 'slug' and it isn't unique then a WP_Error will be passed back. If you don't pass any slug, then a unique one will be created for you.

The slug, which already exists and is already set to "my-old-name" does not update to "my-new-name" when I run the above function.

Is this intended? Do I need to manually code the slug generation and change it myself in the arguments?

1

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.

  • what if said slug already exists? Does sanitize_title check that? ( aka I would prefer if it adds a 2 ). Also, what would happen if I passed a blank slug in? I will try this when I get a chance, thank you! – Jacob Raccuia Apr 10 '15 at 20:12
  • @JacobRaccuia : see the edit. I believe-- untested but based on reading the code-- that if you pass a blank slug the system will attempt to use the name argument. – s_ha_dum Apr 10 '15 at 22:07
  • So after some testing, it does indeed look like using 'slug' => '' will call upon wp_unique_term_slug. I appreciate the long and thoughtful answer! – Jacob Raccuia Apr 13 '15 at 23:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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