Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save angelochillemix/cb7dc773685383b302b57d7b881a0e63 to your computer and use it in GitHub Desktop.
Save angelochillemix/cb7dc773685383b302b57d7b881a0e63 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;
//Remove parent directory
$dir_path = substr(ltrim($parsed_url['path'], '/'), strpos(ltrim($parsed_url['path'], '/'), '/'));
$file = ABSPATH . $dir_path;
// Check if the resulting file exists and return its full path
if (file_exists( $file)) return $file;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment