We all know you can use wp_get_attachment_url() to return an attachment’s URL by passing in the ID, but what about the reverse scenario?

There are a lot of long-winded examples of how to get an attachment ID by URL floating around the interwebs. Most of them limit results to only returning images or use expensive DB queries. Really, there should be a function for this in core, but there isn’t.

Needless to say, I wasn’t really happy with any of the solutions I found people using, so I decided to take a stab at it.

Below is the most lightweight method I’ve come up with (so far) to get an attachment ID by passing through an attachment URL.

Example usage

Just as an example, this would echo the attachment ID integer of test-image.jpg onto the page:

<?php echo fjarrett_get_attachment_id_by_url( 'https://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg' ) ?>

This would echo the same result as above because we are ignoring www usage in the URL being passed through:

<?php echo fjarrett_get_attachment_id_by_url( 'https://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg' ) ?>

This would echo nothing, because the image doesn’t exist in the WordPress uploads directory:

<?php echo fjarrett_get_attachment_id_by_url( 'https://frankiejarrett.com/foo/test-image.jpg' ) ?>

And finally, this would also echo nothing because the URL of the file is pointing to an external domain:

<?php echo fjarrett_get_attachment_id_by_url( 'http://www.anotherdomain.com/wp-content/uploads/2013/05/test-image.jpg' ) ?>


We managed to fetch an attachment ID in just a few lines of code with no expensive DB queries! Awesome 😎

Now you can do cool things like turn a URL into an absolute path:

$url = 'https://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg';
$attachment_id = fjarrett_get_attachment_id_by_url( $url );
$path = ( $attachment_id ) ? get_attached_file( $attachment_id ) : null;
echo $path;

For more information about what was used in this function, please see:

Was this code helpful to you? Let me know in the comments!