Wrap all post images inside a div element

Try using PHP’s regular expression find/replace function—preg_replace()—in a filter on the the_content hook.

function breezer_addDivToImage( $content ) {

   // A regular expression of what to look for.
   $pattern = '/(<img([^>]*)>)/i';
   // What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
   $replacement="<div class="myphoto">$1</div>";

   // run preg_replace() on the $content
   $content = preg_replace( $pattern, $replacement, $content );

   // return the processed content
   return $content;
}

add_filter( 'the_content', 'breezer_addDivToImage' );

Note that this will only affect images inside post content.

If you want to wrap images that occur outside of the post body (such as featured images or images in custom fields), the most efficient way is probably to find where they occur and add the div wrapper to your theme file.

Leave a Comment