Add custom class and ID to all images in wordpress posts and pages, easy way to add custom class and ID to wordpress image automatically, simple wordpress function and easy to use.

How To Add Custom Class To Images

Using the content filter, we will add custom class to all wordpress images, read this tutorial about the content filter.

Add Class To Images

Copy function code and paste it in your functions.php file, function code:

function WPTime_add_custom_class_to_all_images($content){
    /* Filter by Qassim Hassan - http://wp-time.com */
    $my_custom_class = "my-class1 my-class2"; // your custom class
    $add_class = str_replace('<img class="', '<img class="'.$my_custom_class.' ', $content); // add class
    return $add_class; // display class to image
}
add_filter('the_content', 'WPTime_add_custom_class_to_all_images');

Your custom class is “my-class1 my-class2”, if you want more class, enter space between class, for example “my-class1 my-class2”, but if one class, enter class name only “my-class1”, custom class will be in all images, in new posts and old.

ID To Images

If you want to add ID to images, use this function:

function WPTime_add_id_to_all_images($content){
    /* Filter by Qassim Hassan - http://wp-time.com */
    $my_id = "my-id"; // your id
    $add_id = str_replace('<img ', '<img id="'.$my_id.'" ', $content); // add id
    return $add_id; // display id to images
}
add_filter('the_content', 'WPTime_add_id_to_all_images');

Your ID is “my-id”, change it.

Add Custom Class And ID

If you want to add custom class and ID to images, use this function:

function WPTime_add_custom_class_and_id_to_all_images($content){
    /* Filter by Qassim Hassan - http://wp-time.com */
    $my_custom_class = "my-class1 my-class2"; // your custom class
    $my_id = "my-id"; // your id
    $add_class_and_id = str_replace('<img class="', '<img id="'.$my_id.'" class="'.$my_custom_class.' ', $content); // add class and id
    return $add_class_and_id; // display class and id to image
}
add_filter('the_content', 'WPTime_add_custom_class_and_id_to_all_images');

Please note: don’t add multiple IDs! one ID only.

Another Way

You can use this way, but working with new posts only.

Do you want to add class to links? Use Extend Link Plugin, All-In-One.