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)
Try
attachment_url_to_postid
function.More details
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
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/
Late answer: so far, the best solution I've found out there, is the following:
http://frankiejarrett.com/get-an-attachment-id-by-url-in-wordpress/
I think It's the best for 2 reasons:
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:
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.