When inserting images into posts auto add a wrapping div

I think it is a better idea, if you filter the output, the the_content and add the div on all images. It is better for feature, if you will remove this markup, it is not inside the database.

add_filter( 'the_content', 'fb_add_div_to_img' );
function ( $content ) {

    // find img and add markup
    return $content;
}

To find and replace the img in content use a regex, like this

If you use the regex preg_match_all( '/\<img [^>]*src=\"([^\"]+)\"[^>]*>/', $content, $arr, PREG_PATTERN_ORDER); then you get a array. Inside this array you find the img tag with all values, $arr[0]. Enhance this var with your markup and return to the var $content. Also here a example from the web. Additional hint for a regex tester, there I like: Regex Test Tool

But it is also possible to add markup on insert images in the editor:

add_filter( 'image_send_to_editor', 'fb_give_linked_images_class', 10, 8 );
function fb_give_linked_images_class( $html, $id, $caption, $title, $align, $url, $size, $alt="" ){

    $html; //contains the string you need to edit, you might want to consider to rebuild the complete string.

    return $html;
}

Leave a Comment