Constrain RSS feed images to a specific width

If you like my WordPress work, check out my new plugin, Bylines. Thanks!

Formatting email newsletters is really hard. When using a RSS feed to deliver content to an email newsletter, you may need to ensure inline images are restricted to a specific width.

The following code snippet constrains images in RSS feed content to 600 pixel width. When an image is larger than 600px wide, it scales the image’s attributes proportionally to fit within 600px. Images already 600px wide or less are ignored.

This approach is also non-destructive. Because the approach filters the rendered output, and not the content in the database, it’s safe to change (or remove) at any future date.

“`
/**
* Constrain images in RSS feed content to 600px (or less)
*/
function hb_constrain_rss_images( $content ) {

$width_constraint = 600;
// Identify all images in the body content
if ( preg_match_all( ‘#]+((width|height)=[“\’]([^”\’]+)[“\’])[^>]+((width|height)=[“\’]([^”\’]+)[“\’])[^>]+>#i’, $content, $matches ) ) {
// Process each image
foreach( $matches[0] as $i => $match ) {
// Identify the width and height attributes on the image
$wk = ‘width’ === $matches[2][ $i ] ? 3 : 6;
$hk = 3 === $wk ? 6 : 3;
// Width is already less than constraint, which means we don’t need to constrain
if ( (int) $matches[ $wk ][ $i ] <= $width_constraint ) { continue; } // Calculate new width / height values, based on constraint $new_width = $width_constraint; $new_height = ( $new_width / $matches[ $wk ][ $i ] ) * $matches[ $hk ][ $i ]; $search_replace = array( $matches[ $wk - 2 ][ $i ] => ‘width=”‘ . $new_width . ‘”‘,
$matches[ $hk – 2 ][ $i ] => ‘height=”‘ . $new_height . ‘”‘,
);
// Replace existing image reference in the body content
$new_img = str_replace( array_keys( $search_replace ), array_values( $search_replace ), $matches[0][ $i ] );
$content = str_replace( $matches[0][ $i ], $new_img, $content );
}
}
return $content;
}
add_filter( ‘the_content_feed’, ‘hb_constrain_rss_images’ );
“`