search

Home  >  Q&A  >  body text

Get attachment ID of file path in WordPress

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粉716228245P粉716228245421 days ago600

reply all(2)I'll reply

  • P粉254077747

    P粉2540777472023-10-21 00:51:08

    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.

    reply
    0
  • P粉282627613

    P粉2826276132023-10-21 00:44:12

    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

    reply
    0
  • Cancelreply