Search code examples
phpwordpressurlrelative-path

PHP tidy up relative url / up one level


On my Wordpress site I've moved my uploads directory and everything is working correctly, but the URLs to images and attachments just look a bit ugly:

eg http://<website>/wordpress/../media/uploads/2013/09/<image>.jpg

I'd like to tidy up the "up one level" part of the URL, so it looks something like this, http://<website>/media/uploads/2013/09/<image>.jpg, instead.

Anyone know of a nice PHP function to tidy the URLs?


Solution

  • You can put the following in the functions.php file in your theme folder:

    function canonicalize($address)
    {
        $address = explode('/', $address);
        $keys = array_keys($address, '..');
    
        foreach($keys AS $keypos => $key)
        {
            array_splice($address, $key - ($keypos * 2 + 1), 2);
        }
    
        $address = implode('/', $address);
        $address = str_replace('./', '', $address);
    }
    

    to be able to do something like:

    echo canonicalize('http://www.example.com/something/../else''); 
    //http://www.example.com/else
    

    from http://www.php.net/manual/de/function.realpath.php#71334