How to Automatically Add a Class to the Attachment Images

When you add an image to WordPress post content something similar to following HTML code is generated.

Useful Read: How to Style WordPress Contact Form 7 Plugin using Bootstrap CSS Framework

<img class="alignnone size-full wp-image-884" src="http://localhost/wordpress/wp-content/uploads/2014/07/photo1.jpg" alt="photo" width="500" height="667" />

By default, WordPress assign some classes to the <img> tag along with some other HTML attributes. But, what if you want to assign your own  custom class along with these defaults without having to manually assign it whenever you add a new image.

Fortunately, WordPress comes with a built-in hook which allows to modify the class attribute completely.

All you need to do is copy the following code and paste it inside your functions.php file located inside your theme directory.

function add_image_class($class) {
    $class .= ' img-responsive';
    return $class;
}
add_filter('get_image_tag_class', 'add_image_class' );

Don’t forget to replace img-responsive with your own class name.

After dropping the following code inside functions.php file our previous HTML output will look something like this,

<img class="alignnone size-full wp-image-884 img-responsive" src="http://localhost/wordpress/wp-content/uploads/2014/07/photo1.jpg" alt="photo" width="500" height="667" />

 

0 Comments

Leave a Comment.