How to apply the Bootstrap CSS class .img-fluid to all content images in your WordPress theme

To apply the Bootstrap CSS class .img-fluid to all content images in your WordPress theme, you can use the the_content filter to modify the output of post content before it’s displayed. Follow these steps:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function add_img_fluid_class($content) {
// Find all <img> tags and add the .img-fluid class
$content = preg_replace('/(<img[^>]+)(class="[^"]+")?([^>]*>)/', '$1class="img-fluid"$3', $content);

return $content;
}
add_filter('the_content', 'add_img_fluid_class');

This code snippet defines a function add_img_fluid_class() that uses a regular expression to find all <img> tags in the post content and adds the .img-fluid class. The function is then hooked to the the_content filter, which applies the changes before the content is displayed.

  1. Click “Update File” to save the changes.

Now, all images in your post content will have the .img-fluid class applied to them.

Keep in mind that this solution relies on regular expressions, which may not be foolproof in all cases. Be sure to test your changes thoroughly on your staging site or local development environment before applying them to your live site.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *