Auto match 404 strings and redirect

A recent client had a product list built from posts and pages. I transformed it into a WooCommerce store. Google had indexed their inventory as posts and pages. We┬áneeded to rewrite these automatically to the new style listing of WooCommerce’s products custom post type.

I wrote a small 404 handler that would search WooCommerce products for the requested page slug (these always matched).

The following code would be in your theme’s 404.php page.

$parsed_url = explode('-',basename($_SERVER['REDIRECT_URL']));
 
if (isset($parsed_url[0])) {
 
	$parsed_url[0] = sanitize_title($parsed_url[0]);
 
	$search_posts = get_posts(array(
		'post_type' => 'products',
		'suppress_filters' => TRUE,
		'posts_per_page' => '1',
		's' => $parsed_url[0]
	));
 
	if ($search_posts) {
		wp_safe_redirect(get_permalink($search_posts[0]->ID), 301);
		exit();
	}
}

Author: Kieran Barnes

Kieran is a PHP developer with 15 years commercial experience. Specialist in WordPress, CakePHP, CubeCart and all things PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *