Redirect URLs With Capital Letters to Lowercase
Permanently redirects addresses typed or linked with capital letters, such as /About-Us/, to their lowercase form, avoiding duplicate URLs and broken links.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
$uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
$path = (string) wp_parse_url( $uri, PHP_URL_PATH );
if ( '' === $path || ! preg_match( '/[A-Z]/', preg_replace( '/%[0-9A-Fa-f]{2}/', '', $path ) ) ) {
return;
}
$lower = preg_replace_callback( '/(%[0-9A-Fa-f]{2})|([A-Z]+)/', function ( $m ) {
return '' !== $m[1] ? $m[1] : strtolower( $m[2] );
}, $path );
if ( null === $lower || $lower === $path ) {
return;
}
$query = (string) wp_parse_url( $uri, PHP_URL_QUERY );
$scheme = wp_parse_url( home_url(), PHP_URL_SCHEME );
$host = wp_parse_url( home_url(), PHP_URL_HOST );
$port = wp_parse_url( home_url(), PHP_URL_PORT );
wp_safe_redirect( $scheme . '://' . $host . ( $port ? ':' . $port : '' ) . $lower . ( '' !== $query ? '?' . $query : '' ), 301 );
exit;
}, 1 );
Notes
Encoded characters such as %C3%A9 are left as they are. Query strings are kept unchanged.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.