Tutorial WordPressaside

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 for wp_get_attachment_image_src() and as get_post_meta().


Adding alt text to a post thumbnail

While working on a custom navigation using WP_Query and has_post_thumbnail for an icon I ran into an accessibility concern. By default, the_post_thumbnail will not display an alt tag when rendered in the browser. In the following code snippet I add an alt tag using the image file’s title.


// The Post Array
$args = array(
	'category_name'	=> 'disasters, emergency-procedures',
	'orderby'	=> 'title',
	'order'		=> 'ASC',

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
	while ( $the_query->have_posts() ) {
		echo '<a href="' . get_permalink() . '">'; 
		echo '<article class="emergency-icon">';
			// check if the post has a Post Thumbnail assigned to it.
			if ( has_post_thumbnail() ) {

					array('alt' => get_the_title() )

			echo '<span class="entry-title">' . get_the_title() . '</span>';
		echo '</article>';
		echo '</a>';
	/* Restore original Post Data */
} else {
	// no posts found

In short the code above starts with a query that looks for categories slugged”disasters” and emergency-procedures then orders the results by title in ascending order.

Customized html is then wrapped around the results along with an alt attribute taken from the image’s title then included within the img tag.

Technically speaking, it would be more appropriate to use the alt field set for the image. However, alt text has to be generated manually where as the title is automatically created when media is uploaded to the library.

Tutorial WordCamp WordPress

Dipping into Child Themes

Theme development looks complicated but it doesn’t have to be. WordPress Child Themes give you the power to progressively enhance a theme and adapt it to suit your needs.