Get Attachment Id by File Path in Wordpress

I know the path of the file and I like to get the attachment ID.

There's a function wp_get_attachment_url() which requires the ID to get the URL but I need it reverse (with path not URL though)

1

7 Answers

UPDATE: since wp 4.0.0 there's a new function that could do the job. I didn't tested it yet, but it's this:


OLD ANSWER: so far, the best solution I've found out there, is the following:

I think It's the best for 2 reasons:

  • It does some integrity checks
  • [important!] it's domain-agnostic. This makes for safe site moving. To me, this is a key feature.
5

I used this cool snipped by pippinsplugins.com

Add this function in 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 = '

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

// print the id
echo $image_id;

Original post here:

Hope ti helps ;) Francesco

5

Try attachment_url_to_postid function.

$rm_image_id = attachment_url_to_postid( ' );
echo $rm_image_id;

More details

1

None of the other answers here appear to work properly or reliably for a file path. The answer using Pippin's function also is flawed, and doesn't really do things "the WordPress Way".

This function will support either a path OR a url, and relies on the built-in WordPress function attachment_url_to_postid to do the final processing properly:

/**
 * Find the post ID for a file PATH or URL
 *
 * @param string $path
 *
 * @return int
 */
function find_post_id_from_path( $path ) {
    // detect if is a media resize, and strip resize portion of file name
    if ( preg_match( '/(-\d{1,4}x\d{1,4})\.(jpg|jpeg|png|gif)$/i', $path, $matches ) ) {
        $path = str_ireplace( $matches[1], '', $path );
    }

    // process and include the year / month folders so WP function below finds properly
    if ( preg_match( '/uploads\/(\d{1,4}\/)?(\d{1,2}\/)?(.+)$/i', $path, $matches ) ) {
        unset( $matches[0] );
        $path = implode( '', $matches );
    }

    // at this point, $path contains the year/month/file name (without resize info)

    // call WP native function to find post ID properly
    return attachment_url_to_postid( $path );
}
2

Cropped URLs

None of the previous answers supported ID lookup on attachment URLs that contain a crop.

e.g: /uploads/2018/02/my-image-300x250.jpg v.s. /uploads/2018/02/my-image.jpg

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.