Skip to content

Instantly share code, notes, and snippets.

@joemcgill
Created December 28, 2015 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joemcgill/b19a1094bd3494b193e0 to your computer and use it in GitHub Desktop.
Save joemcgill/b19a1094bd3494b193e0 to your computer and use it in GitHub Desktop.
CSS Tricks Responsive Image Filter
function wp_css_tricks_images_responsive( $content ) {
/**
* Find all instanced of your custom image markup in the content and bail early
* if none are found.
*/
if ( ! preg_match_all( '/<figure [^>]+>\s+<img [^>]+>/', $content, $matches ) ) {
return $content;
}
// Set up arrays to hold your images and a set of IDs that we'll cache later.
$selected_images = $attachment_ids = array();
// Loop through all our matches and process each one to add responsive images.
foreach( $matches[0] as $match ) {
// Bail early if a `srcset` already exists or if we can't find a media ID in the class.
if ( false === strpos( $match, ' srcset=' ) && preg_match( '/media-([0-9]+)/i', $match, $class_id ) &&
( $attachment_id = absint( $class_id[1] ) ) ) {
// Break the image tag out of our pattern.
preg_match( '/<img [^>]+>/', $match, $image );
/*
* If exactly the same image tag is used more than once, overwrite it.
* All identical tags will be replaced later with 'str_replace()'.
*/
$selected_images[ $image[0] ] = $attachment_id;
// Overwrite the ID when the same image is included more than once.
$attachment_ids[ $attachment_id ] = true;
}
}
if ( count( $attachment_ids ) > 1 ) {
/*
* Warm object cache for use with 'get_post_meta()'.
*
* To avoid making a database call for each image, a single query
* warms the object cache with the meta information for all images.
*/
update_meta_cache( 'post', array_keys( $attachment_ids ) );
}
foreach ( $selected_images as $image => $attachment_id ) {
$image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
$content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
}
return $content;
}
add_filter( 'the_content', 'wp_css_tricks_images_responsive' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment