Attachment Image Snippet

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().

Soon I Will Be Invincible

Reading the beginning of chapter thirteen from Soon I Will Be Invincible gave me a sensible chuckle.

Feeling rather full of himself after avoiding detection at a super hero funeral the antagonist of the story relaxes in a coffee shop.

I close my eyes, for a moment. There are days when you just don’t feel all that evil.

Doctor Impossible

Hey. Um. Honey? I think that guy over there is Doctor Impossible.

Coffee shop onlooker

Just a reminder that even super villains suck at information security.