Automatically Add Attributes to All Images in WordPress Posts

Print View Mobile View

The below snippet will allow you to add an attribute to all images embedded in a WordPress post.

function sumtips_image_attribute($content) {
       global $post;
       $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
       $replacement = '<a$1href=$2$3.$4$5 attribute="attribute_value"';
       $content = preg_replace($pattern, $replacement, $content);
       return $content;
}
add_filter('the_content', 'sumtips_image_attribute');

Replace attribute="attribute_value" to whatever attribute you need.

Example:

function sumtips_image_attribute($content) {
       global $post;
       $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
       $replacement = '<a$1href=$2$3.$4$5 rel="lightbox"';
       $content = preg_replace($pattern, $replacement, $content);
       return $content;
}
add_filter('the_content', 'sumtips_image_attribute');

If you want to use the post title as the title attribute of the images anchor tag, replace line 4 in the above code with the following:

$replacement = '<a$1href=$2$3.$4$5 attribute="attribute_value" title="'.$post->post_title.'"$6>';