I was trying to figure out how to get the absolute directory of an attachment post in WordPress. Turns out there’s no easy function that can give you one, but there is one called wp_upload_dir which will give you an array of the upload directories and URLs. So here’s the secret sauce:
$url = wp_get_attachment_url( $post_ID ); $uploads = wp_upload_dir(); $file_path = str_replace( $uploads['baseurl'], $uploads['basedir'], $url );
The $file_path
variable will now contain an absolute path (filesystem path, not URL) to the location of your attachment file. You can then use it when sending attachments with wp_mail
or perhaps when serving the file dynamically. Enjoy!
It’s more reliable to retrieve relative (to uploads) file path from metadata and concatenate rather than replace. But replace also works… Usually. :)
Rarst, I agree, and especially if you’re running on a Windows environment where backslashes are used, in which case you’d have to replace them before replacing the path. Thanks for the heads up!