Skip to content

Instantly share code, notes, and snippets.

@kamalahmed
Created February 14, 2019 17:23
Show Gist options
  • Save kamalahmed/cb1ef003d384715ad38fffff379d5a4c to your computer and use it in GitHub Desktop.
Save kamalahmed/cb1ef003d384715ad38fffff379d5a4c to your computer and use it in GitHub Desktop.
You can convert an attachment url to its absolute path in WordPress using this function.
<?php
/**
* Get the attachment absolute path from its url
*
* @param string $url the attachment url to get its absolute path
*
* @return bool|string It returns the absolute path of an attachment
*/
function attachment_url_to_path( $url )
{
$parsed_url = parse_url( $url );
if(empty($parsed_url['path'])) return false;
$file = ABSPATH . ltrim( $parsed_url['path'], '/');
if (file_exists( $file)) return $file;
return false;
}
@hayatbiralem
Copy link

It's nice to have, thank you 👍

@kamalahmed
Copy link
Author

It's nice to have, thank you 👍

You are most welcome 😄

@angelochillemix
Copy link

angelochillemix commented Nov 27, 2021

Thanks for the code snippet 👍

I get $file with duplicated folder coming from both ABSPATH and $parsed_url['path'].

image

image

Following works in my case, removing the parent directory from the parsed path:
image

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment