0

Is there a possible way to get the alt text from the media file by just knowing the URL? For example, if the path to my image is /bc/wp-content/uploads/placeholder-image.png is there a way (just by using that URL) to get the alt text of that image. I know you usually need the ID and such, trying to find a way around this.

PHP

<img src="/bc/wp-content/uploads/placeholder-image.png" alt="<?php /* do something */ ?>" />
2

Using the function found here, you could add this to your functions.php

// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
    return $attachment[0]; 
}

But to use it, you need the full image URL.

$img_url = get_bloginfo('url') . '/bc/wp-content/uploads/placeholder-image.png';

if ( $img_id = pippin_get_image_id($img_url) ) {
    // Using wp_get_attachment_image should return your alt text added in the WordPress admin.
    echo wp_get_attachment_image( $img_id, 'full' );
} else {
    // Fallback in case it's not found.
    echo '<img src="' . $img_url . '" alt="" />';
}
1

This is a slightly modified version of the Pippin Function. Since it returns a post ID we can use it to get the alternative text which is saved as Post Meta:

/**
 * Get image alt text by image URL
 *
 * @param String $image_url
 *
 * @return Bool | String
 */
function image_alt_by_url( $image_url ) {
    global $wpdb;

    if( empty( $image_url ) ) {
        return false;
    }

    $query_arr  = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid='%s';", strtolower( $image_url ) ) );
    $image_id   = ( ! empty( $query_arr ) ) ? $query_arr[0] : 0;

    return get_post_meta( $image_id, '_wp_attachment_image_alt', true );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.