admin管理员组

文章数量:1317898

Currently by default image have similar classes

<img class="size-full wp-image-8996" src=".jpg">

What i am trying here to add a class as img-fluid to all the attachments in posts not the thumbnails.

<img class="img-fluid size-full wp-image-8996" src=".jpg">

How could it be done?
Any Idea will be appreciated! Please help me

Currently by default image have similar classes

<img class="size-full wp-image-8996" src="https://nepaltimes/wp-content/uploads/2018/04/31043884_1792179470828697_8330507756888915968_n.jpg">

What i am trying here to add a class as img-fluid to all the attachments in posts not the thumbnails.

<img class="img-fluid size-full wp-image-8996" src="https://nepaltimes/wp-content/uploads/2018/04/31043884_1792179470828697_8330507756888915968_n.jpg">

How could it be done?
Any Idea will be appreciated! Please help me

Share Improve this question edited Apr 28, 2018 at 15:25 Nimesh asked Apr 28, 2018 at 2:40 NimeshNimesh 4413 gold badges7 silver badges19 bronze badges 1
  • Are you using a function to display image? Like the_post_thumbnail() ? – Colin Smillie Commented Apr 28, 2018 at 16:14
Add a comment  | 

3 Answers 3

Reset to default 4

You can use the filter get_image_tag_class which exists exactly to do what you want:

add_filter('get_image_tag_class','wpse302130_add_image_class');

function wpse302130_add_image_class ($class){
    $class .= ' img-fluid';
    return $class;
    }

cjbj's answer seems more better but i am still leaving this for reference that we can also do these ways.

There are 3 way.

  1. Solve it in frontend(with Javascript)
  2. Solve it in backend(with PHP)
  3. Solve it manually

First one, you run javascript to add class like:

ref.: w3school

function myFunction() {
  var element = document.getElementById("myDIV");
  element.classList.add("mystyle");
} 

while you loop through all the img tags.

Second one, you have to parse post contents with PHP DOM and do the same thing like Javascript.

Third one, you edit the post with text and add your class manually.

These above solutions are great but for an incredibly simple fix for this specific issue. I've added the CSS for img-fluid onto the standard classes that wordpress adds to it's images:

.size-thumbnail, .size-medium, .size-large, .size-full {
    max-width: 100%;
    height: auto;
}

This may not be as elegant as the above solutions but performance wise it's just a little chunk of CSS.

本文标签: functionsHow to add css class to image attached in all the posts