Skip to content

Instantly share code, notes, and snippets.

@mor10
Created May 28, 2014 01:46
Show Gist options
  • Save mor10/23f2ae1b4d973ef31de8 to your computer and use it in GitHub Desktop.
Save mor10/23f2ae1b4d973ef31de8 to your computer and use it in GitHub Desktop.
Basic function to create responsive featured image in WordPress. Code to be added to functions.php.
<?php
/**
* Create function my_responsive_thumbnail() to output responsive featured image
* Function can be called from within the loop of any template file using my_responsive_thumbnail(get_the_ID());
*/
function my_responsive_thumbnail($post_id){
// Get the featured image ID
$attachment_id = get_post_thumbnail_id($post_id);
// Get the alt text or set the $alt_text variable to the post title if no alt text exists
$alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
if ( !$alt_text ) { $alt_text = esc_html( get_the_title($post_id) ); }
// Get the info for each image size including the original (full)
$thumb_original = wp_get_attachment_image_src($attachment_id, 'full');
$thumb_large = wp_get_attachment_image_src($attachment_id, 'large-thumb');
$thumb_medium = wp_get_attachment_image_src($attachment_id, 'medium-thumb');
$thumb_small = wp_get_attachment_image_src($attachment_id, 'small-thumb');
// Create array containing each image size + the alt tag
$thumb_data = array(
'thumb_original' => $thumb_original[0],
'thumb_large' => $thumb_large[0],
'thumb_medium' => $thumb_medium[0],
'thumb_small' => $thumb_small[0],
'thumb_alt' => $alt_text
);
// Echo out <picture> element based on code from above
echo '<picture>';
echo '<!--[if IE 9]><video style="display: none;"><![endif]-->'; // Fallback to <video> element for IE9
echo '<source srcset="' . $thumb_data['thumb_large'] . ', ' . $thumb_data['thumb_original'] . ' x2" media="(min-width: 800px)">';
echo '<source srcset="' . $thumb_data['thumb_medium'] . ', ' . $thumb_data['thumb_large'] . ' x2" media="(min-width: 400px)">';
echo '<source srcset="' . $thumb_data['thumb_small'] . ', ' . $thumb_data['thumb_medium'] . ' x2">';
echo '<!--[if IE 9]></video><![endif]-->'; // Fallback to <video> element for IE9
echo '<img srcset="' . $thumb_data['thumb_small'] . ', ' . $thumb_data['thumb_medium'] . ' x2" alt="' . $thumb_data['thumb_alt'] . '">';
echo '</picture>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment