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

Force WordPress to remember you for a longer period of time than 14 days

A co-worker asked if it was possible to ask WordPress to keep an active session longer than one day or 14 days if you click the “Remember Me.”

Which brought to a post on WordPress Development Stack Exchange where Alex Mills ( Viper007Bond) had solved this problem a year ago. This serves as a reminder of how important he was to the WordPress community. I frequently stumble upon his answers and no longer have the opportunity to thank him for taking the time.

// Extends user session to one year
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );

function keep_me_logged_in_for_1_year( $expirein ) {
    return 31556926; // 1 year in seconds
}

I find the code hilarious in that it would extend period for a year which is clearly excessive. I’m sure he meant that as a joke. 😀