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?

6 s
6

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

Leave a Comment