How to automatically add a CSS class to images inserted in WordPress posts

To automatically add a CSS class to images inserted in WordPress posts, you can use the get_image_tag_class filter. Here’s how to do it:

  1. Log in to your WordPress admin dashboard.
  2. Go to “Appearance” > “Theme Editor.”
  3. In the right sidebar, locate and click on the “functions.php” file.
  4. Add the following code snippet at the end of the file:
function custom_image_class($class) {
    $class .= ' your-custom-class';
    return $class;
}
add_filter('get_image_tag_class', 'custom_image_class');

Replace your-custom-class with the desired CSS class you want to add to the images in your posts.

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

This code snippet will automatically add the specified CSS class to every image inserted into your WordPress posts. Remember to create a backup of your site before making changes to the code, as editing your theme’s functions.php file can have unintended consequences if not done correctly.

Note: This method only applies to images inserted into posts using the default WordPress editor. If you’re using a page builder or any other custom plugin to create content, you may need to use a different method or consult the plugin documentation to add the CSS class automatically.

Leave a Reply

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