Can you please let me know how I can add a class to an image getting from Post Content? I have a page called promotion and it only contains an image which I uploaded through Add Media now in page I have

<div class="container">
  <?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>  
        <?php the_content(); ?>
    <?php endwhile; ?>
<?php endif; ?>  

and at front end I am getting this:

<img class="size-full wp-image-2202 alignright" src="http://rumioptical.com/wp-content/uploads/2014/11/Promotion-Banner.jpg" alt="Promotion Banner" width="800" height="640">

but I need only to get

<img class="img-responsive" src="http://rumioptical.com/wp-content/uploads/2014/11/Promotion-Banner.jpg" alt="Promotion">

removing the size-full wp-image-2202 alignright classes and width and height attributes and adding the img-responsive class?

2 Answers 2


Most likely your images outputted to the_content() were added manually via the Media button in the admin. You should be able to add your own class from that point. The default class are added by the WP system when choosing alignment, etc in the Insert Media modal.

enter image description here


The moment an image is inserted in a post, the hook image_send_to_editor is called. The input to the hook is the html and perhaps also a caption shortcode. Like this:

[caption id="attachment_999" align="alignright" width="150"]
<a href="http://www.example.com/wp-content/uploads/2016/06/my-image.jpg">
<img src="http://www.example.com/wp-content/uploads/2016/06/my-image-150x150.jpg" alt="My colourful image" width="150" height="150" class="size-thumbnail wp-image-101" />
Look at how colourful this is!

The hook intercepts this string, allowing you to manipulate it:

add_filter ('image_send_to_editor', 'wpse_209128_filter_image');
function wpse_209128_filter_image ($html) {
    // first, remove the image and caption dimensions
    $html = preg_replace ('/(width|height)=\"\d*\"\s/', '', $html);
    // second, replace the class on the img tag
    $html = preg_replace ('/class=\"([^"]*)\", 'class="img-responsive"', $html);
return $html;

Beware that once the img is inserted in the post the user can still edit the html and screw things up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.