WordPress 301 redirect from Upercase url’s to lowercase

WordPress 301 redirect from Upercase url’s to lowercase

Reading Time: 2 minutes

This is something stupid I had to do when some Google crawl errors occurred on webmaster tools, and I saw some deprecated stuff on the web and had to trick it a little bit.

function isPartUppercase($string) {
  return (bool) preg_match('/[A-Z]/', $string);
}

add_action('parse_request', 'parseUppercase');

function parseUppercase($wp) {

  $query = $wp->query_vars;
  $query = $query['pagename'];

  if(isPartUppercase($query)){
    $link = site_url().'/'.strtolower($query);

    if($_SERVER['QUERY_STRING']){
      $link.= '?'.$_SERVER['QUERY_STRING'];
    }

    wp_redirect( $link , 301 );
    exit;
  }
}

 

Add this snippet to your functions.php file.

So here we use the ‘parse_request’ hook which handles the request for a page from the server and runs when someone makes a request. We add a ‘parseUppercase’ function which gets the $wp global wp variable and gets the name of the page in the request we are converting it to lowercase, and concatenating the query variables (if exist) to the redirected URL with wp_redirect function.