Search Query for 404 Error Pages Wordpress


When I trimmed down my categories in Wordpress I paid special attention to make sure that all my new 404 errors would be redirected to a logical place because of the restructure. That's fine since there are only about 19 re-directs, but after removing 100 tags I decided there had to be a better way to handle these missing tags than an additional 100 redirects.

I decided my search tool had to be string enough to handle it for me, and why shouldn't my 404 page just immediately re-direct my users right to the search. One less click for them!

So below my redirects on my 404 page, but above the Wordpress template tag "get_header()" I put in this snippet:

$request = $_SERVER['REQUEST_URI']; // This line was implemented in the 404 redirect fix

$tag_base = get_option('tag_base');
if(empty($tag_base))    $tag_base = 'tag';
$pattern = '/\/('.$tag_base.')\/([a-z0-9-]*)\//i';

if(preg_match($pattern, $request, $matches)){
    $search_for = str_replace('-', ' ', $matches[2]);
    $search_for = urlencode(trim($search_for));

    //Content hasn't moved but for our purposes this 301 header might be more useful than a 404
    header("HTTP/1.1 301 Moved Permanently");
    header('Location: /?s='.$search_for);
    die();
}

Now if I requested the page /tag/boston/, since I no longer have tags by the name "boston" it would redirect to a search for "boston" just like the search box does.

Since the main purpose of this modification is to logically replace old tags I also took into consideration that Wordpress hyphenates multi-word tags, so I added a string replacement to replace the hyphen with a space.
So requesting /tag/flickr-explore/ would search for the query term "flickr explore" instead of "flickr-explore" which would yield no results.

No perfect but a great quick and dirty solution!

Update it even now accounts for any change you've made to the tag base.

So if in the Wordpress Options>Permalinks you changed the tag base to be '/tagging/' or '/folksonomy/' instead of the default '/tag/' then it will account for that changing without you having to update my snippet.
Ain't I so smart :)

Popularity: 27% [?]


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!