WordPress: Automatically add class to inserted Images


In wordpress you can add images to posts, pages and other post types via the “Add Media”-button. Sometimes it is practical to automatically add an additional class to those images.

Lightbox to this picture is added via the class “td-modal-image”.

For example on this page, images get displayed in a lightbox, if you click on them. For this feature every image needs the class td-modal-image. But it is a pain in the ass to manually add this to every image. So I automated this one.

This Php-Code goes into the functions.php:

function nddt_add_class_to_images($class){
    $class .= ' td-modal-image';
    return $class;

Filters in wordpress are an easy way to change outputs. You can have more than one filter, so make sure that they don’t cancel each other out. If necessary you can change the order in which they are executed.

We use the filter “get_image_tag_class” to change the classes for images beeing added via the standart editor of wordpress.

Don’t forget the empty space in front of the additonal class, as this could be the space between the new class and the classes that have already been added.

You can find the wordpress documentation here.

If you are already on it, you might be intressted in pre-selecting “Link to Media File” in the Add Media Menu. Check out the solution here.

Feel free to ask your questions in the comments.


Please enter your comment!
Please enter your name here