How to find attachment by it's name?

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?

Topic post-thumbnails attachments images Wordpress

Category Web


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;}

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;
}

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.
}

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.


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)


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');

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.