4

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
    Oct 8 '13 at 6:16
  • Echoing Wyck, because Googling "wordpress get attachment id from guid" or "wordpress get attachment id from name" brings up several solutions. Oct 8 '13 at 9:04
  • @helgatheviking and did you try it or just googled?
    – Kirix
    Oct 8 '13 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. Oct 8 '13 at 10:45
10

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
    Oct 8 '13 at 8:50
  • ok, by name I thought it to be post name Oct 8 '13 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. Oct 8 '13 at 9:46
  • 1
    @user1692333 Great!!! Why don't you post what you did? Oct 17 '13 at 6:51
  • 4
    using the namespace wp_ for none wordpress owned functions is bad
    – Toskan
    Oct 12 '16 at 20:10
6

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
    Jan 20 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
    Feb 9 at 16:39
  • 1
    Fair enough @Robbiegod! Found your answer useful too :)
    – Tami
    Feb 11 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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