Get attachment ID of file path in WordPress
P粉716228245
P粉716228245 2023-10-20 09:02:14
0
2
592

I know the path to the file and want to get the attachment ID.

There is a function wp_get_attachment_url() which requires the ID to get the URL, but I need it to be reversed (although the path is not the URL)

P粉716228245
P粉716228245

reply all(2)
P粉254077747

Update: Since wp 4.0.0 there is a new function that does the job. I haven't tested it yet, but it goes something like this:

https://developer.wordpress.org/reference/functions/attachment_url_to_postid/


Old answer: The best solution I've found so far is the following:

https://frankiejarrett.com /2013/05/get-an-attachment-id-by-url-in-wordpress/

I think this is the best for two reasons:

  • It will do some integrity checks
  • [important! ] It has nothing to do with domain. This helps move the site safely. To me, this is a key feature.
P粉282627613

I used this cool screenshot from pippinsplugins.com

Add this function to your functions.php file

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

Then use this code in your page or template to store/print/use the ID:

// set the image url
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';

// store the image ID in a var
$image_id = pippin_get_image_id($image_url);

// print the id
echo $image_id;

Original post here: https://pippinsplugins.com/retrieve-attachment-id-from-imageurl/

Hope it helps ;) Francis

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template