Open Source Code

WordPress Redirect Old Query Strings to New Permalinks

Overview

Author
FWD:labs

Requirements
WordPress 4.9+

Version (Last Updated)
1.00 (2017-11-17 09:10:05)

License

The MIT License (MIT)

Copyright (c) 2016 FWD:labs

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Instructions

1. See config notes for editing your site's .htaccess file for two specifics tailored to your site and your needs.
2. Save this file as "redirect.php" in your theme's folder.
3. Make sure your new WordPress site uses "Custom Fields" where key #1 is called "meta_key" and stores the old site's query key (e.g. example); key #2 is called "meta_value" and matches what the old site's query value was, e.g. 12345

Code

<?php

// CONFIG
// These steps can be adjusted to modify a behavior to this application

// EDIT YOUR .HTACCESS
// 1. Find the initial lines, e.g. #BEGIN WordPress, RewriteBase /
// 2. Add these two lines:
// 		RewriteCond %{QUERY_STRING} ^example=(.*)$
// 		RewriteRule ^ /wp-content/themes/theme/redirect.php?via=example [QSA,L,R]
// 3. Replace "example" on both lines to match the query string your old site used
// 4. Replace "theme" on the second line to match your theme's URI

// DEBUG
$debug = false; // If set to "true," view this file on your web server to turn the redirector into a non-redirecting debugger, with viewable readouts in the browser

// DEFAULTS
// These set up the application to run properly and do not need adjustments

// Debugging this file may lead it to cache, especially if R=301 in the controlling .htaccess file; this code helps prevents that
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// In order to use WordPress' query_posts(), we need to boot up WordPress
// Not knowing the server(s) path, this method relies on the file being in the theme folder to get wp-load.php to load
define('WP_USE_THEMES', false);
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );

// These variables will be filled in if there's a match later in the code
$getExample = "";

// These variables will be filled in if there's a match later in the code
$metaKey = "";
$metaValue = "";

// APPLICATION
// This code runs based on the variables above

// We'll now define things based on the QSA (e.g. old URL pathways which used query strings) via the .htaccess rewrite to this file
// If you have more scenarios, copy these if statements and add after the one below; you'll need to do the same copy/paste in .htaccess, too
if (isset($_GET['example'])) {
	$getExample = $_GET['example'];
	$metaKey = "example";
	$metaValue = sanitize_meta($getExample); // Use WordPress' sanitize_meta() to prevent XSS
}

// We set these in default, and if they were modified by a GET query, let's check those choices with WordPress
if ($metaKey <> "" && $metaValue <> "") {	
	
	// This is one method to query posts in WordPress
	query_posts("meta_key=$metaKey&meta_value=$metaValue");
	if (have_posts()) {
			
		// In theory, we may have multiple results from the query above, so this will loop through everything and only fire on one of the results
		while (have_posts()) {
		    	
			the_post();
			$postID = get_the_ID() ;

			// SUCCESS
			// Show success as echo for debug mode, or else redirect with 301 header
			if ($debug == true) { 
				echo "SUCCESS: matching post ID ($postID) found using meta key/value lookup";
			} else {
		        
				// Get the WordPress permalink with just the post ID
				$permalink = get_permalink($postID);
			        
				// Check that the function returned a value
				if ($permalink) {
			        
					// Tell the browser it's a 301 and then redirect the browser
					header ("HTTP/1.1 301 Moved Permanently");
					header ("Location: ".$permalink);
						
				}
				
			}
		        
		}
	} else {
			
		// ERROR
		// Meta key and value were found, but no match found on this WordPress site using meta key and value
		if ($debug == true) { 
			echo "SUCCESS: meta key ($metaKey) and value ($metaValue) were found, but there was still an ERROR: no match was found on this WordPress site";
		} else {
			// When in doubt, redirect the user to the new home page
			header ("Location: /");	
		}
		    
	}
	
} else {
	
	// ERROR
	// Query string is empty
	if ($debug == true) {
		echo "ERROR: variables metaKey and metaValue remained empty because 'example' could not be found";
	} else {
		// When in doubt, redirect the user to the new home page
		header ("Location: /");
	}

}

?>

Changelog

Feedback

Questions, comments, concerns or ideas about this? Please let us know.

Twitter   Facebook   Instagram