0

add_action('wp_head', 'custom_url_case_insensitive_redirect');
function custom_url_case_insensitive_redirect() {
    global $wp;
    $requested_url = home_url($wp->request);
    $file_name = basename($requested_url);
         // Scan all files and folders recursively
    $files = getAllFiles(ABSPATH);
        // var_dump($files);
    $count = 0;
    foreach ($files as $file_path) {
        //if($count<10){
        if (!(strpos($url, "wp-content") !== false || strpos($url, "wp-admin") !== false || strpos($url, "wp-includes") !== false)) {
        // Normalize the file path and filename to lowercase for comparison
        $lowercaseFile = strtolower($file_path);
       // echo $lowercaseFile. '<br>';
        $replace_url =  str_replace("/home/stgdom/public_html//"," https://stgdom.org/",$lowercaseFile);
                 $lowercaseRequest = strtolower($requested_url);
         $decode_request = trim(utf8_decode(urldecode($lowercaseRequest)));
        $decode_replace = trim(utf8_decode(urldecode($replace_url)));
                 if(trim($lowercaseRequest) == trim($replace_url) || $decode_request == $decode_replace || strcasecmp($lowercaseRequest, $replace_url) == 0 || strcasecmp($decode_request, $decode_replace) == 0) {
            $file_path_new =  str_replace("/home/stgdom/public_html//"," https://stgdom.org/",$file_path);
                         //echo utf8_decode(urldecode($lowercaseRequest)).' File:- '.$replace_url.' New: '.$file_path_new.'<br>';
            wp_redirect(trim($file_path_new), 301);
            exit();
        }
         $count++;
        }
         //exit();
    }
}
 function getAllFiles($dir) {
    $files = array();
    $all = scandir($dir);
     foreach ($all as $file) {
        if ($file != '.' && $file != '..') {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($path)) {
                $files = array_merge($files, getAllFiles($path));
            } else {
                $files[] = $path;
            }
        }
    }
     return $files;
}

admin Edited question April 25, 2024
Add a Comment