How to get image ID by URL
I like most developers don’t like work for some web builders or themes, especially when we need provide accessibility (enabling access for people with disabilities). As is known, one of the requirements of accessibility it’s don’t use empty alt and title attributes for images. But in addition, very preferably use meaningful text. Today we’ll review how add alt & title to image attributes if we have only URL image.
Problem: How to get image alt and image title by image URL.
Solution: For example, we have next code:
<img src="'.esc_url($PROGUARDS_GLOBALS['logo']).'" class="logo_main" alt="Some Alt" title="Some Title">
We need get image ID, after then we can get title & alt of image. In functions.php paste next code:
<?php
function get_image_id_by_url( $url ) {
global $wpdb;
$image = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url ));
if(!empty($image)) {
return $image[0];
}
return false;
}
In the code place:
<?php
$image_url = 'https://sitename.com/image_name.jpg';
$image_id = get_image_id_by_url( $image_url );
// Get Alt Image By Image ID
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
// Get Title Image By Image ID
$image_title = get_the_title($image_id);
or add one more function to functions.php:
<?php
function get_image_alt_and_title( $image_id ) {
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($image_id);
image = [
'alt' => $image_alt,
'title' => $image_title,
];
return $image;
}
in this way we will eventually in functions.php:
<?php
function get_image_id_by_url( $url ) {
global $wpdb;
$image = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url ));
if(!empty($image)) {
return $image[0];
}
return false;
}
function get_image_alt_and_title( $image_id ) {
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($image_id);
image = [
'alt' => $image_alt,
'title' => $image_title,
];
return $image;
}
At the place call:
<?php
$image_url = 'https://sitename.com/image_name.jpg';
$image_id = get_image_id_by_url( $logo_image_url );
$image_info = get_image_alt_and_title( $logo_image_id );
echo '<img src="' . esc_url( $logo_image_url ) . '" class="logo_main" alt="' . esc_attr( $image_info['alt'] ) . '" title="' . esc_attr( $image_info['title'] ) . '">';
Sources: