File path without domain name from wp_get_attachment_url()

wp_get_attachment_url() process full file path like

http://example.com/wp-content/uploads/2014/12/aura.mp3

I want the url without http://example.com/
So, I want above example as wp-content/uploads/2014/12/aura.mp3 instead of http://example.com/wp-content/uploads/2014/12/aura.mp3. How to do it?

Related posts

Leave a Reply

4 comments

  1. You can really easily explode it by / and then take the part with index 3. Example

    $url = wp_get_attachment_url(id); //id is file's id
    $urllocal = explode(site_url(), $url)[1]; //output local path
    
  2. You can use PHP’s function explode.

    Here is the code:

        <?php
             $image_url = wp_get_attachment_url( 9 ); //ID of your attachment
             $my_image_url = explode('/',$image_url,4);
             echo $my_image_url[3];
        ?>
    
  3. You can implode your entire url on / and array_slice from the end, then implode it back in on /.

    $url = wp_get_attachment_url($item->ID); //id is file's id
    $url_relative = implode(array_slice(explode('/', $url),-3,3),'/');
    //Returns: 2019/08/image.jpg
    

    That way if your WordPress is on a subdomain or localhost or the images are on S3 it won’t crash.