WordPress: template_redirect

December 2nd, 2008

Before I upgraded to wordpress 2.6, I had URLs using tags like this:

After I upgraded I realized I liked categories better (they can have parent categories).  So no more tags, all categories, but the problem was that google (and others) still link to /tag/travel/ which ended on a 404 page. Since I had no tags, I decided to redirect all my  /tag/xxxx to /cat/xxxx – I also prefer /cat/xxx to /category/xxx, which I changed in Settings-Permalinks.  Here’s how I did the redirect exactly:

Add the following to the end of ../wp-content/themes/<current_theme>/functions.php file

// added at the end of functions.php file, in my current theme's directory
add_action ('template_redirect', 'check_for_tag_404');

// custom function to redirect old tag links to new cat links
function check_for_tag_404()
$pat = '/^\/tag\/(.*)$/';

// return if this URL does not begin with "/tag/"
if (!preg_match( $pat, $_SERVER["REQUEST_URI"])) return;

$uri = preg_replace( $pat, '/cat/$1', $uri);
$location = "http://" . $_SERVER["HTTP_HOST"] .  $uri;
header("Location: $location");

Big Ups to this template_redirect dude for giving me a clue.