jordanmaslyn
1/8/2016 - 5:16 PM

PHP Redirects using the CSV plugin

PHP Redirects using the CSV plugin

<?php

// include this file in your root index.php file to load before Wordpress loads.
//
// Related Gists:
// CSV template: https://gist.github.com/jordanmaslyn/94d450814d921420408a
// Plugin code: https://gist.github.com/jordanmaslyn/fbbcc571e6717e66b880
//
// Make sure to replace THEME_NAME with your theme's actual name in the line below.

$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$base_uri = $uri_parts[0];
if(substr($base_uri, -1) == '/') {
  // trim trailing slash
  $base_uri = substr($base_uri, 0, -1);
}

$csv_url = dirname(__FILE__) . '/wp-content/themes/unboxed/functions/modules/redirects.csv';
$file_handle = fopen($csv_url, 'r');
$i = 0;
while (!feof($file_handle) ) {
  $csv[] = fgetcsv($file_handle, 2048);
  if ($csv[$i][0] == $base_uri) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: '.$csv[$i][1]);
    exit();
  }
  $i++;
}
fclose($file_handle);

?>