6

When I'm in the Wordpress editor and I add an external image with the 'img' button, my html result wil be like this:

<img src="http://example.com/image.jpg" alt="image" />

How can automatically have a class being added to the img tag? Like this:

<img class="my-img-class" src="http://example.com/image.jpg" alt="image" />

I would like to apply the same principle to the 'Add Media' option. This output is like this:

<a href="mywordpressdomain/image.jpg"><img src="mywordpressdomain/image.jpg" alt="image" width="872" height="867" class="alignnone size-full wp-image-59" /></a>

And I want the output to be like this:

<a href="mywordpressdomain/image.jpg"><img src="mywordpressdomain/image.jpg" alt="image" width="872" height="867" class="alignnone size-full my-img-class" /></a>

I'm new with PHP, so I'm not sure how to this via a filter. I'm started like this, but I don't know what to do next:

function image_tag_class($class, $id, $align, $size) {
    return $align;
}
add_filter('get_image_tag_class', 'image_tag_class', 0, 4);
7

You could do like this:

function image_tag_class($class) {
    $class .= ' my-custom-class';
    return $class;
}
add_filter('get_image_tag_class', 'image_tag_class' );

in case you wanna know more about actions and hooks.

Difference Between Filter and Action Hooks?
add_filter
add_action

  • thanks, I've tried your function, but no class is added to the img tag when I add an image link in the post editor. – Eric Jul 22 '14 at 17:17
  • When you add an image to the post editor from the add media button it's not coming with the 'my-custom-class' css class? Before I send it to you, I've made testes here, and it was working Or you want the class when you have image link? – Marcos Rodrigues Jul 22 '14 at 17:39
  • Yes sorry it's working, I was in the wrong theme:$ Thank you – Eric Jul 22 '14 at 18:13
  • it's however not working when I insert a link via the 'link' button (insert from url) in the post editor. Also, how do I remove the default wordpress class 'wp-image-59' ? – Eric Jul 22 '14 at 18:14
  • Note that the class will be added to new images only. It will not be added to old images, because the HTML is already generated in the content editor. – karimhossenbux Mar 27 '17 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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