Monday, January 13, 2014

Alter path alias programmatically for an existing taxonomy term

Here's a method to alter the path alias (if you're using the pathauto module) of an existing taxonomy term programmatically. Here we shall be doing this in a hook_update_N(). It is quite un-intuitive given the lack of proper documentation as to how to alter the alias of an existing term. Here is my trial & error method:

 * Re-alias 'Trailer' term & create a redirect from its old path to the new alias.
function xxxxx_update_7007() {
  // 'Trailer' term.
  $term = taxonomy_term_load(20);
  // Set 'Generate automatic URL alias' to FALSE to allow custom alias setting later.
  $term->path['pathauto'] = FALSE;

  // Create a new alias
  $new_path = path_load('taxonomy/term/20');
  $new_path['alias'] = 'trailers';

  // Setup redirect from the old url 'trailer' to 'trailers'
  $redirect = new stdClass();

      'source' => 'trailer',
      'source_options' => array(),
      'redirect' => 'trailers',
      'redirect_options' => array(),
      'language' => LANGUAGE_NONE,

  module_invoke('redirect', 'save', $redirect);

In the above example, we are changing the path of a term from '/trailer' to '/trailers' and setting up a redirect from the old path so that users don't get lost (plus it's better for SEO).

We first have to unset the 'Generate automatic URL alias' option and save the term. Then create the new alias, followed by adding the redirect from the old alias.

No comments: