This snippet for wp_get_attachment_image_src frequently appears in my theme development to select an image by its unique ID in the WordPress media library.
Handy for instances where logos, banners, or any other image frequently recurs on a website and you’d rather store that image in the media library where it can be replaced or modified dynamically.
// replace 7 with unique ID number of image
$image_attributes = wp_get_attachment_image_src( $attachment_id = 7, 'full' );
// retrieves alternative text from image information
$alt = get_post_meta( $attachment_id , '_wp_attachment_image_alt', true );
if ( $image_attributes ) {
echo '<img src="'. $image_attributes[0] .'" width="' . $image_attributes[1] . '" height="' . $image_attributes[2] . '" alt="' . $alt . '" />';
}
How it works
- Set the unique id number in the snippet
- Displays the image and relevant attributes
This code is based on the official Code References at WordPress.org for wp_get_attachment_image_src() and as get_post_meta().