How do you find a file in the media library using the file URL?

WordPress Development Asked by Garrett Massey on November 7, 2020

We have about 2000 files in our media library and we are working on an audit to organize the files and create a name hierarchy.

But until that is done, I am trying to locate a handful of specific files to replace. I don’t know what the files are named in WordPress, I only have the URL to download the file.

Is there a way to search for the file in the dashboard using the URL?

One Answer

Based on my research, you would need to run a query on directly on the database using WPDB. So you would do something like this:

Add this in your functions.php file:

// retrieves the attachment ID from the file URL
function get_image_id($image_url) {
    global $wpdb;
    $the_attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
    return $the_attachment[0]; 

And then you can apply it wherever you like this way:

$attachment_url = '';
$attachment_id = get_image_id($image_url);

$attachment_id will have the attachment ID so you can do whatever you want with it.

Correct answer by Tets Tets on November 7, 2020

Add your own answers!

Related Questions

Co-authors plus problems with query_post

1  Asked on October 30, 2021 by wallace-ferreira


wp_get_archives() not working for my custom post type

1  Asked on October 30, 2021 by best-dev-tutorials


Run Username SQL Query from WordPress Child Theme Functions File

1  Asked on October 30, 2021 by moa-andersen


Change wordpress admin home page

1  Asked on October 30, 2021 by bendict-mutua


How to move a post from one category to another

1  Asked on October 30, 2021 by sajeergraphix


Query custom post type custom meta key

1  Asked on October 30, 2021 by user1551496


Ask a Question

Get help from others!

© 2023 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP