I have a function that contains a wpdb query. It's supposed to get the image alt text, based on the url of the image. This is the function:
// retrieves the attachment alt from the file URL
function get_image_alt_from_url($image_url) {
global $wpdb;
$id = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
if ($id) {
return get_post_meta($id[0], '_wp_attachment_image_alt', TRUE);
}
return false;
}
It used to work, but now it returns false every time. Upon debugging the function, I found that the $id
variable is null.
I wonder if this has anything to do with upgrading PHP to 8.0, and if so, how to get around it. It still works on my local site, so I doubt it's related to a wp core update.
WordPress: 6.2.2 PHP: 8.0 Hosted on Kinsta
Thank you so much for your help,
Jill
WPDB::get_col()
should always return an array, notnull
, even if you pass itnull
as a query. Where in the code snippet were you testing$id
and finding itnull
?$id = attachment_url_to_postid($image_url);
. Once you have that, you can get it's alt via$alt = get_post_meta($id, '_wp_attachment_image_alt', TRUE);