How to wrap every image in a post with a div?

When I add an image to a post I want it to be in a div e.g. , and I want that to be done automatically, so I don’t have to do that in HTML editor.
I don’t want to use js to accomplish this and by the way I want to know how to automatically add custom classes to a image in a post. Cheers!

Related posts

Leave a Reply

4 comments

  1. By default images already have unique class’s but this depends on your theme. Use firebug and hover over the images and you should see stuff like class="aligncenter size-full wp-image-1525".

    If you want to change the class or id or alter any attributes of the image you can use the get_image_tag filter. For example,

    add_filter('get_image_tag_class','my_custom_class');
    
    function my_custom_class($class){
    $class='my_custom_name';
    return $class;
    }
    
  2. I have found the following code while making some research. You can easily wrap a Post image in a Div by using the built-in filter of WordPress i.e image_send_to_editor. Here is an example,

    if( is_admin() ) {
    
        add_filter( 'image_send_to_editor', 'wp_image_wrap_init', 10, 8 );  
        function wp_image_wrap_init( $html, $id, $caption, $title, $align, $url, $size, $alt ) {
            return '<div id="wp-image-wrap-'. $id .'" class="wp-image-wrap">'. $html .'</div>';
        }
    
    }
    

    Thanks to http://wpalkane.com/hacks/wrap-post-image-inside-div-automatically/

  3. You answer was close but not enough because the hook checkpoint for get_image_tag_class() only changes the class attribute. So I was playing around and find out that the right thing for wrapping each image is get_image_tag() so the code goes like this :

    function my_image_tag($html, $id , $alt, $title){
    
    $html = "<div class='**wrap-div**'>" . $html . "</div>";
    return $html;
    }
    
    add_filter('get_image_tag','my_image_tag',10,4);
    

    You answer was partially right so it’s the best one 😉
    Cheers mate and thanks for your help.

  4. the answers here can be divided into 2 methods:

    1) functions, that work in POST EDITOR (back-end) (see posted answers)
    2) functions, that work in POST OUTPUT (front-end)

    p.s. another methods to change front-end output:

    a)

    function my_image_class_filter($classes) {
        return $classes . ' another-image-class';
    }
    add_filter('get_image_tag_class', 'my_image_class_filter');
    

    b)

    function add_post_image_class($content) {
        return preg_replace('/<img(.*?)class="(.*?)"/', '<img $1 class="$2 YOUR_CLASS_NAME"', $content);
    }
    add_filter( 'the_content', 'add_post_image_class' );