AnswerBun.com

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 = 'http://example.com/wp-content/uploads/2020/10/28/just_for_the_lolz.jpg';
$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

Sending current featured image to email

0  Asked on January 26, 2021 by hm-dadou

   

wp_mail doen’t send mails whit attachment

2  Asked on January 25, 2021 by stonesmith

   

How to get category id of current post?

5  Asked on January 24, 2021 by jrcollins

 

preg_replace regex problem

1  Asked on January 23, 2021 by jim-worrall

   

How to display a sidebar only for blog?

1  Asked on January 23, 2021 by johny-j

 

Fill post titles from post content?

1  Asked on January 23, 2021 by cecily

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP