I know the path of the file and I like to get the attachment ID.
There’s a function wp_get_attachment_url()
which requires the ID to get the URL but I need it reverse (with path not URL though)
I know the path of the file and I like to get the attachment ID.
There’s a function wp_get_attachment_url()
which requires the ID to get the URL but I need it reverse (with path not URL though)
You must be logged in to post a comment.
UPDATE: since wp 4.0.0 there’s a new function that could do the job. I didn’t tested it yet, but it’s this:
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
OLD ANSWER: so far, the best solution I’ve found out there, is the following:
https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/
I think It’s the best for 2 reasons:
I used this cool snipped by pippinsplugins.com
Add this function in your functions.php file
Then use this code in your page or template to store / print / use the ID:
Original post here: https://pippinsplugins.com/retrieve-attachment-id-from-image-url/
Hope ti helps 😉
Francesco
Try
attachment_url_to_postid
function.More details
None of the other answers here appear to work properly or reliably for a file path. The answer using Pippin’s function also is flawed, and doesn’t really do things “the WordPress Way”.
This function will support either a path OR a url, and relies on the built-in WordPress function attachment_url_to_postid to do the final processing properly:
Cropped URLs
None of the previous answers supported ID lookup on attachment URLs that contain a crop.
e.g:
/uploads/2018/02/my-image-300x250.jpg
v.s./uploads/2018/02/my-image.jpg
Solution
Micah at WP Scholar wrote a blog post and uploaded the code to this Gist. It handles both original and cropped URL lookup.
I included the code below as a reference but, if you find useful, I’d encourage you to leave a comment on his post or star the gist.
Another pro with this solution is that we leverage the
WP_Query
class instead of making a direct SQL query to DB.Find IDs for resized images, PDFs and more
Like GFargo pointed out, most of the answers assume the attachment is an image. Also attachment_url_to_postid assumes a url (not a file path).
I believe this better answers the actual question when supplied a file (with path):
Based on the answer from @FrancescoCarlucci I could do some improvements.
Sometimes, for example when you edit an image in WordPress, it creates a copy from the original and adds the copys upload path as post meta (key
_wp_attached_file
) which is not respected by the answer.Here the refined query that includes these edits: