6

Is it possible to get attachment id by its name? And at once may be it's possible to get parent post, to which this attachment is assigned?

4
  • @Wyck, just couldn't find any function to find file by its name.
    – Kirix
    Commented Oct 8, 2013 at 6:16
  • Echoing Wyck, because Googling "wordpress get attachment id from guid" or "wordpress get attachment id from name" brings up several solutions. Commented Oct 8, 2013 at 9:04
  • @helgatheviking and did you try it or just googled?
    – Kirix
    Commented Oct 8, 2013 at 10:28
  • 1
    No I didn't try. My point was that Wyck asked what you'd tried and that there are plenty of functions out there for you to try. If you can tell us what you've tried and precisely what isn't working we can help you tweak that. Also, support threads such as wordpress.org/support/topic/… are marked resolved so someone must have thought the solution was valid. Commented Oct 8, 2013 at 10:45

6 Answers 6

12

You have to write custom code to get the attachment id and post_parent by name/ slug or filename(if it has not been changed during the uploading of files).

Put the below code in your theme's functions.php file

if( ! ( function_exists( 'wp_get_attachment_by_post_name' ) ) ) {
    function wp_get_attachment_by_post_name( $post_name ) {
            $args           = array(
                'posts_per_page' => 1,
                'post_type'      => 'attachment',
                'name'           => trim( $post_name ),
            );

            $get_attachment = new WP_Query( $args );

            if ( ! $get_attachment || ! isset( $get_attachment->posts, $get_attachment->posts[0] ) ) {
                return false;
            }

            return $get_attachment->posts[0];
    }
}

then you can call the function where you need it like below :--

$attachment = wp_get_attachment_by_post_name( $post_name );
// Replace post_name by the name/slug of the attachment
// It will give you an object, which you can render like below to get the ID and post_parent
if ( $attachment ) {
    echo $attachment->ID; // Gives the id of the attachment
    echo $attachment->post_parent; // Gives the post_parent id
    echo $attachment->post_title; // Gives the attachment title.
}
8
  • i don't have the post name, i have only file name
    – Kirix
    Commented Oct 8, 2013 at 8:50
  • ok, by name I thought it to be post name Commented Oct 8, 2013 at 9:06
  • You can try the filename instead of the post_name as the parameter, as WordPress creates the slug for the attachment with the filename until unless it is altered. Commented Oct 8, 2013 at 9:46
  • 1
    @user1692333 Great!!! Why don't you post what you did? Commented Oct 17, 2013 at 6:51
  • 4
    using the namespace wp_ for none wordpress owned functions is bad
    – Toskan
    Commented Oct 12, 2016 at 20:10
8

Another possible approach is directly use $wpdb to do SQL query, in the posts table, with the searched post title, and with post_type "attachment".

function get_attachment_url_by_title( $title ) {
    global $wpdb;

    $attachments = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_title = '$title' AND post_type = 'attachment' ", OBJECT );
    //print_r($attachments);
    if ( $attachments ){

        $attachment_url = $attachments[0]->guid;

    }else{
        return 'image-not-found';
    }

    return $attachment_url;
}
// usage:
get_attachment_url_by_title('your_image_title');

Keep in mind that this code will return the first attachment with this title.


Alternative way, without SQL query. Better in most cases:

function get_attachment_url_by_title( $title ) {

$attachment = get_page_by_title($title, OBJECT, 'attachment');
//print_r($attachment);

  if ( $attachment ){

    $attachment_url = $attachment->guid;

  }else{
    return 'image-not-found';
  }

  return $attachment_url;
}

echo get_attachment_url_by_title('your_image_title');
3

get_page_by_title() will do the trick.

With a full URL as title:

get_page_by_title( pathinfo( 'https://www.example.com/file.jpg' )['filename'], "OBJECT", 'attachment' );

Returns WP_Post Object or Null, if no posts/attachments were found.

1

Base on WordPress Codex,

attachment' - an attachment. Whilst the default WP_Query post_status is 'publish', attachments have a default post_status of 'inherit'. This means no attachments will be returned unless you also explicitly set post_status to 'inherit' or 'any'. (See post_status, below)

1

I just spent a couple of hours trying to solve this very problem. There was a file name that get_page_by_title could not find. @Snade I adapted his answer for my purposes.

I only have the filename and I need to get the url of the image from the media library. Snade was very close, but even still his function didn't given my circumstances. The function he provided did get me into the right direction.

This solution I'll be testing, but seems to work. Basically all I am looking for is the filename in the guid. Since the title stripped off the extension and made spaces, i wasn't able to find this image any other way.

Off to do more testing...

function get_attachment_url_by_guid( $filename ) {
        global $wpdb;

        $ext = array(".png", ".jpg", ".gif", ".jpeg");
        $filename = str_replace($ext, "", $filename);
        $clean_filename = trim(html_entity_decode(sanitize_title($filename)));

    
        $attachments = $wpdb->get_results( "SELECT guid FROM $wpdb->posts WHERE guid LIKE '%$clean_filename%' AND post_type = 'attachment' ", OBJECT );
        //print_r($attachments);
        if ( $attachments ){    
            $attachment_url = $attachments[0]->guid;    
        }else{
            return 'image-not-found';
        }   
        return $attachment_url;
}
3
  • Would be better to $wpdb->prepare the get_results query @Robbiegod
    – Tami
    Commented Jan 20, 2021 at 21:22
  • you got that right! @Tami But this code is only being inside of a plugin that is not distributed. Just a custom plugin for my site. I'll update it in the future. Good call.
    – Robbiegod
    Commented Feb 9, 2021 at 16:39
  • 1
    Fair enough @Robbiegod! Found your answer useful too :)
    – Tami
    Commented Feb 11, 2021 at 0:58
1

I've had to spend way too much time on this as some of the above solutions work in some situations but not others. The sticking point is for attachments uploaded with greater than 2560px resolution. Wordpress appends '-scaled' to the filename returned by get_attached_file(), but this is not reflected in the guid database column.

In the end I traced through the code for get_attached_file() and reverse engineered the following.

function get_attachment_id_by_filename($filename) {
    global $wpdb;
    $attachments = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value like'%$filename'", OBJECT);
    return $attachments[0]->post_id ?? false;}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.