Aslam Shekh
Aslam Shekh

Reputation: 716

Get the Attachment ID from an Image URL in WordPress

I recently needed a way to get the ID of a WordPress image attachment, but I only had the image URL to work with. The problem was complicated by the fact that the image URL could be a thumbnail of the original image attachment, i.e. one of the auto-generated post thumbnail image sizes.

Upvotes: 0

Views: 5072

Answers (2)

Rodgath
Rodgath

Reputation: 575

I know this old but there's a quick solution for this. Use attachment_url_to_postid WordPress function.

Example usage:

echo attachment_url_to_postid( 'http://example.com/wp-content/uploads/2019/07/image-abc.png' );

Output:

45

Upvotes: 9

Alex MacArthur
Alex MacArthur

Reputation: 2286

You'll need to find or make a regex for removing the dimensions from resized versions of image attachments, but here's how you can get the ID of any given attachment URL. Pippin Williamson wrote a brief function for querying the database:

https://pippinsplugins.com/retrieve-attachment-id-from-image-url/

Upvotes: 0

Related Questions