Skip to content

Instantly share code, notes, and snippets.

@halfempty
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halfempty/2e8cd8e5499a3df43bcc to your computer and use it in GitHub Desktop.
Save halfempty/2e8cd8e5499a3df43bcc to your computer and use it in GitHub Desktop.
srcset image tag functions for WordPress
// Image Sizes
add_image_size( 'padmini', 1024 );
add_image_size( 'phone', 1136 );
add_image_size( 'phoneplus', 1334 );
add_image_size( 'padretina', 2048 );
function spellerberg_get_image($imageid,$fallbacksize = 'full') {
$sizes[] = wp_get_attachment_image_src( $imageid, 'padmini');
$sizes[] = wp_get_attachment_image_src( $imageid, 'phone');
$sizes[] = wp_get_attachment_image_src( $imageid, 'phoneplus');
$sizes[] = wp_get_attachment_image_src( $imageid, 'padretina');
$sizes[] = wp_get_attachment_image_src( $imageid, 'full');
$srcset = '';
foreach ( $sizes as $size ) :
$srcset .= $size[0] . ' ' . $size[1] . 'w, ';
endforeach;
$fallback = wp_get_attachment_image_src( $imageid, $fallbacksize);
$alt_text = get_post_meta($imageid, '_wp_attachment_image_alt', true);
if ( !$alt_text || $alt_text == "" ) :
$attachment = get_post($imageid);
$alt_text = $attachment->post_title;
endif;
$output = '<img ';
if ( $srcset != '' ) :
$output .= 'srcset="' . $srcset . '" ';
endif;
$output .= 'src="' . $fallback[0] . '" ';
$output .= 'alt="' . $alt_text . '">';
return $output;
}
function spellerberg_the_image($imageid,$fallbacksize = 'full') {
echo spellerberg_get_image($imageid,$fallbacksize);
}
function spellerberg_get_thumbnail($post_id, $fallbacksize = 'full') {
$imageid = get_post_thumbnail_id( $post_id );
if ( $imageid ) :
return spellerberg_get_image($imageid,$fallbacksize);
endif;
}
function spellerberg_the_thumbnail($post_id, $fallbacksize = 'full') {
echo spellerberg_get_thumbnail($post_id, $fallbacksize);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment