WordPress: template_redirect

December 2nd, 2008

Before I upgraded to wordpress 2.6, I had URLs using tags like this:
http://chadnorwood.com/tag/travel/

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 = $_SERVER["REQUEST_URI"];
$uri = preg_replace( $pat, '/cat/$1', $uri);
$location = "http://" . $_SERVER["HTTP_HOST"] .  $uri;
header("Location: $location");
exit;
}

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


Warning: count(): Parameter must be an array or an object that implements Countable in /nfs/c04/h03/mnt/66006/domains/chadnorwood.com/html/wp-includes/class-wp-comment-query.php on line 405
  1. March 20th, 2009 at 05:25 | #1

    very intresting

  1. No trackbacks yet.