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;
taxonomy_term_save($term);
// Create a new alias
$new_path = path_load('taxonomy/term/20');
$new_path['alias'] = 'trailers';
path_save($new_path);
// Setup redirect from the old url 'trailer' to 'trailers'
$redirect = new stdClass();
module_invoke(
'redirect',
'object_prepare',
$redirect,
array(
'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.
/**
* 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;
taxonomy_term_save($term);
// Create a new alias
$new_path = path_load('taxonomy/term/20');
$new_path['alias'] = 'trailers';
path_save($new_path);
// Setup redirect from the old url 'trailer' to 'trailers'
$redirect = new stdClass();
module_invoke(
'redirect',
'object_prepare',
$redirect,
array(
'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:
Post a Comment