You should only interact with the DB via WP, not directly. It’s not a big deal in your case because you just want to see a value, but you’ll be more aligned with the best practices if you go in trying to solve a problem with $wpdb as a last resort.
In your case, you can try this :
$id = attachment_url_to_postid($image_url); $alt = get_post_meta($id, '_wp_attachment_image_alt', TRUE);
We’ll first get the Post ID from the attachment URL, and then find the alt from that ID. This will do what you want without $wpdb.
That said, let’s try and debug your original problem too!
As @PatJ said,
WPDB::get_col() never returns null, so something’s wrong.
Turn on your debug like this :
define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', false );
The first line enables debugging mode, the second line ensures that debug messages are logged to a wp-content/debug.log file, and the third line prevents debug messages from being displayed on the site.
Run it again. Was an error logged? If not, run this :
Also, after your get_col line, print the last query using the $wpdb->last_query command. This can help you make sure the query is as expected :
Of course, check the image URL too – maybe it’s not correct, or it’s not in the database. It shouldn’t return null, but worth checking.
Also, it’s possible that the issue is not with your $wpdb->get_col() line but the get_post_meta() line. You can debug this by checking what it returns when you give it a known post ID and ‘_wp_attachment_image_alt’ as the meta key.