Skip to content

Instantly share code, notes, and snippets.

@orionrush
Last active August 29, 2015 14:21
Show Gist options
  • Save orionrush/961f0dc20a831ed5cc06 to your computer and use it in GitHub Desktop.
Save orionrush/961f0dc20a831ed5cc06 to your computer and use it in GitHub Desktop.
function to leverage the RICG WP plugin to deliver responsive images with srcset attr using wp_get_attachment_image
/**
* Leverages the RICG WP plugin to deliver responsive images with srcset attr
*
* @param $post_ID
* @param $thumb_id
* @param $size
* @return mixed / wp_get_attached_image markup
*
* @uses PHP 5.2+ due to PATHINFO_FILENAME
* @uses wp_get_attachment_image
*
* @author orionrush
*
*/
function tr_fetch_thumbnail($post_ID, $thumb_id, $thumbnail_size = 'thumbnail', $class = '') {
$alt_text = get_the_title($post_ID); // title of post, not alt text of image attachment
// Get the details of the named thumbnail
$img = wp_get_attachment_image_src( $thumb_id, $thumbnail_size );
// Get its width
$img_w = $img[1];
$srcset_w = ' '. $img_w . 'w';
$atts[] ='';
// Fetch the array of thumbnail sizes as a string for $srcset
if (function_exists('tevkori_get_srcset_array') ){
$sources = tevkori_get_srcset_array( $thumb_id, $thumbnail_size ); //array
if (is_array($sources)){
write_log('starting srcset:');
write_log($sources);
foreach( $sources as $key => $source ) {
// Add retina images
// PATHINFO_FILENAME requires PHP 5.2.0
$retina_file = pathinfo($source, PATHINFO_FILENAME);
$retina_file_ext = pathinfo($source, PATHINFO_EXTENSION);
// remove width attributes that come as part of the srcset info ie ' 350w'
$retina_file_ext = explode(' ', $retina_file_ext);
$retina_file_ext = $retina_file_ext[0];
$retina_dirnam = pathinfo($source, PATHINFO_DIRNAME);
$upload_dir = wp_upload_dir();
// Bulid the expected file name and path
$retina_candidate = $retina_dirnam . '/' . $retina_file . '@2x.' . $retina_file_ext;
$retina_candidate_test = $upload_dir['basedir'] . '/' . $retina_file . '@2x.' . $retina_file_ext;
// Add the 2x image to the array
if (file_exists($retina_candidate_test)) {
$srcset[] = $retina_candidate . ' 2x';
}
// Don't add the image that is in the src to the srcset as well
// But any potential @x2 version has already been added ;)
if ( false === strpos($source, $srcset_w) ) {
$srcset[] = $source;
}
}
}
}
// If we've found any other sizes, other then the target
if (is_array($srcset)){
$srcset = array_keys(array_flip($srcset)); // remove any dupes
$srcset = implode( ', ', $srcset ); // create comma separated list
$atts = array(
'srcset' => $srcset,
'class' => $class,
'alt' => $alt_text
);
} else {
$atts = array(
'class' => $class,
'alt' => $alt_text
);
}
return wp_get_attachment_image( $thumb_id, $thumbnail_size, false, $atts );
}
@orionrush
Copy link
Author

In this example the class isn't filtered for any baddies, in my case that happens earlier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment