Redirect product variation SKU URLs to parent

Fixes 404s of old product slugs that were converted to variations. 301 redirects traffic to the new parent product matched by SKU and pre-selects the variation.

add_action( 'template_redirect', function() {

	// 404 Situations Only
	if( ! is_404() ) {
		return;
	}

	// Get URI
	$uri = parse_url( $_SERVER['REQUEST_URI'] );

	// Get URI Path
	if( empty( $uri['path'] ) ) {
		return;
	}
	$path = untrailingslashit( $uri['path'] );

	// Product URLs Only
	if( ! preg_match( '#/product/(.*)#', $path, $matches ) ) {
		return;
	}

	// Find Product
	$product_id = wc_get_product_id_by_sku( $matches[1] );
	if( $product_id ) {
		$product = wc_get_product( $product_id );

		// Redirect
		wp_redirect( $product->get_permalink(), 301 );
		exit;

	}

} );

How to use

  1. Log into a staging, development, or locally hosted clone of your site
  2. Install and activate Code Snippets
  3. WP Admin > Snippets > Add New
  4. Copy and paste the code from the Description tab above
  5. Check to ensure formatting came over properly and no syntax errors show up in the editor
  6. Customize the code as desired
  7. Add a meaningful title
  8. Select whether to run on front-end or back-end (or both)
  9. Click “Save and Activate”
  10. Test your site to ensure it works
  11. Disable if any problems, or recover
  12. Repeat for live environment

License

All code snippets are licensed GPLv2 (or later) matching WordPress licensing.

Disclaimer of warranty:

Except when otherwise stated in writing the copyright holders and/or other parties provide the program as-is without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.

Support

  1. Describe the issue and what you’ve observed.
  2. Describe your expected outcome(s).
  3. List steps to reproduce the issue.
  4. Optionally provide screen-shot or video URLs.