Get Image Alt Text and Title from a URL in WordPress

How to get the image alt and title by the image URL

Like most developers, I do not like working with some page builders and themes, especially when the site has to be accessible (usable by people with disabilities). One of the accessibility requirements is that images do not have empty alt attributes, and the text should be meaningful. Today we will look at how to add the alt and title to an image when we only have its URL.

Problem: How to get the image alt and title by the image URL?

Solution: For example, a theme prints its logo like this, with the alt written in the code:

<?php
echo '<img src="' . esc_url( $theme_options['logo'] ) . '" class="logo_main" alt="Some Alt" title="Some Title">';

The alt and title are stored with the attachment in the Media Library, so first we need the image ID, and then we can get its alt and title.

Step 1. The image ID by URL

WordPress has a function for this, attachment_url_to_postid(). Add the helper functions to functions.php:

<?php
function get_image_alt_and_title( $image_id ) {
    return array(
        'alt'   => get_post_meta( $image_id, '_wp_attachment_image_alt', true ),
        'title' => get_the_title( $image_id ),
    );
}

Step 2. Use it in the template

<?php
$image_url  = $theme_options['logo'];
$image_id   = attachment_url_to_postid( $image_url );
$image_info = $image_id ? get_image_alt_and_title( $image_id ) : array( 'alt' => '', 'title' => '' );

echo '<img src="' . esc_url( $image_url ) . '" class="logo_main" alt="' . esc_attr( $image_info['alt'] ) . '" title="' . esc_attr( $image_info['title'] ) . '">';

If there is an ID, it is even simpler to let WordPress build the whole tag, with alt, srcset and sizes: echo wp_get_attachment_image( $image_id, 'full', false, array( 'class' => 'logo_main' ) );

Why not the guid

The first version of this code searched the image by the guid column:

<?php
function get_image_id_by_url( $url ) {
    global $wpdb;
    return (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $url ) );
}

It works only while the URL is exactly the one used at upload. After a move to another domain or to HTTPS the guid stays old and nothing is found. attachment_url_to_postid() compares the file path in the uploads folder, so the domain does not matter.

NOTE: Both ways find only the original file. A URL of a resized copy (image-300×200.jpg) returns 0: remove the size suffix from the URL before the search, or store the image ID instead of the URL in the theme options.

Sources:

  1. https://wordpress.stackexchange.com/questions/193196/how-to-get-image-title-alt-attribute