WordPress Filter Examples – Changing Attributes When Adding Images to Posts
June 5th, 2010 by
Typically, when you add an image to your posts, wordpress assigns certain attributes to the img tag, depending on what you chose in the image upload editor form.
The following selection set…

Will result in the following image tag added to your post’s HTML code:
<img src="http://www.webtechwise.com/wp-content/uploads/2010/06/rss-icon.jpg" alt="" title="rss-icon" width="30" height="43" class="aligncenter size-full wp-image-1525" />
However, in some cases you may want to edit these attributes to suit your needs.
Like in many other WordPress tweaks, the add_filter function comes to play, so this is a great way to learn how to use filters and what do apply_filters and add_filter mean exactly.
The get_image_tag function (below) is included in WordPress core files (specifically, in the wp-includes/media.php file).
This function creates the img tag for the image you inserted. As you can see, it handles some important attributes for your image, including ID, title, alt, align and size.
function get_image_tag($id, $alt, $title, $align, $size='medium') {
list( $img_src, $width, $height ) = image_downsize($id, $size);
$hwstring = image_hwstring($width, $height);
$class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
$class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" '.$hwstring.'class="'.$class.'" />';
$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
return $html;
}
Line 5 above (highlighted), includes the apply_filters call, which is called a hook, or in other words, an invitation for you to rewrite the function specified in the hook (in this case, set a new class for the image).
As I explained in this post, it is not wise to edit WordPress core files directly.
Instead, you should create a new filter function in the functions.php file located in your WordPress theme folder.
For the example, let’s set the class of the image to always be “post_image”:
Add the following filter function to functions.php:
function my_image_tag_class($class){
$class='post_image';
return $class;
}
add_filter('get_image_tag_class','my_image_tag_class');
If you take another look at the get_image_tag function, you will see that there is one more apply_filters hook in line 7 – $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
This hook, invites you to rewrite the entire get_image_tag function with all the image attributes and not just its class.
For the example, let’s set the alt attribute to always have the same value as the title attribute.
To rewrite the entire get_image_tag function, add the following filter function to functions.php:
function my_image_tag($html, $id , $alt, $title){
$html = str_replace('alt=""','alt="'.$title.'"',$html);
return $html;
}
add_filter('get_image_tag','my_image_tag',10,4);
Note that in line 5 (highlighted above), the add_filter call now contains 2 more parameters that did not exist in the previous add_filter call. The first parameter is the priority of the filter, and the second parameter is the number of acceptable arguments in the function. I left the priority to default (10) and I set the acceptable args to 4, because I need to pass the $title attribute’s value to the function.
Got any questions or comments? Shoot!

Nice tip. Your code can replace the SEO Image plugin. That’s very good: simpler solution for a good result
Thanks man. I’m glad you like it
Hi,
Could you explain more about rewriting the 2 functions my_image_tag_class and my_image_tag? Do I need to edit both of them and where should I call them?
Thanks.
Hi Tek3D. These 2 filters do not depend on each other so you don’t have to use both, unless you want to both edit the image class attribute and other attributes of the image.
my_image_tag_class is specific for the image class, while my_image_tag enable editing all image attributes.
You should place the filter functions in your functions.php theme file
Thanks Omer,
I want to ask 1 more question. Where would I define the “post-image” class? I am not a web developer so I couldn’t understand this.
Take a look at line 2 at the second code block. It states $class=’post_image’;
Wow Great tip.Surely I’ll apply in my blog.Thanks for sharing.
Hi Omer, this is way over my head, so I need to start with a basic question, why would I want to change this attribute and how will it help me? Can you give me an example of an image with the filter vs. without the filter? Thanks for your patience with me!
Hi ileane! always nice to see you here.
The example in this post shows you how you can change the default attributes when adding an image in the admin.
If you add an image when in HTML view, you will notice that it automatically adds class=”alignnone size-large wp-image-2649″ to your image. I explain here how you can change that default WordPress behavior by using Filters.
Ok, got it now. I never add images in HTML view (but on Blogger I need to embed YouTube videos in HTML view) and it seems I change the attributes each time I add something. HA! Thanks for explaining!
Great tip and easy to follow. I have it working on a site i’m building. Is it possible to have all the images within a post linked to a particular website using this function.
I’d also like to change this website for each post I make, without creating a new link for each picture.
Good question Mose, you can use the filter in the get_image_send_to_editor function.
This function is located in the wp-admin/includes/media.php.
The parameter you are looking for is $url.
Is it possible to set the ‘rel’ tag of a newly posted image using this method? I am using a lightbox script which needs ‘gallery’ appended to the ‘rel’ tag to link multiple images in a gallery.
I’ve had a look through the ‘media.php’ file but I couldnt see anything which might do this.
Rich,
You can use the same filter I use in the above example – $html = apply_filters( ‘get_image_tag’, $html, $id, $alt, $title, $align, $size );
only instead of these attributes, you can pass a rel attribute..
this is useful. It works well for me except i was looking to add a class to the a-tag the image tag in contained in. any ideas?
Hi Frank, would you like this class attribute to be the same for each time you add an image?
hi Omer thanks for the quick response. yes i do. just to clarify instead of having the class added to the img tag i would like it to be added to the a tag the image is contained in.
so with your code I would get (using class=”special”)..
but I would like to have
Frank, you need to somehow overwrite the function get_image_send_to_editor. This function doesn’t seem to have a call for apply_filter that relates to the attributes of the a tag, so I’m not sure how.
Perhaps copying this function to your function.php file and add that specific class you wanted would do the trick.
Hi Omer! Your description is great, but i looking for something more. I would like to insert the IMG tag into a SPAN, to reach the needs of our design.
Could you help me, how to start?
Hugo, thanks. Before I answer your question, do you need a span tag around each and every image you add to your posts or just in particular cases?
Yes Omar. I need a SPAN tag around every image that came across posts, through the_content().
Finally i modified your code to this:
function span_my_image_tag($html, $id , $alt, $title){
$html = str_replace('alt=""','alt="'.$title.'"',$html);
$html = str_replace('<img','',' />',$html);
return $html;
}
add_filter('get_image_tag','span_my_image_tag',10,4);
but at first sight i hope i could find a better and nice solution like remove_filter(‘wp_get_attachment_link’) .. and apply a new filter to do what i want, but it doesnt works :S
function span_my_image_tag($html, $id , $alt, $title){
$html = str_replace('alt=""','alt="'.$title.'"',$html);
$html = str_replace('<img','< span class="imgcanvas" >',' />< /span >',$html);
sorry, i need to replace to <-> because the editor strips out the span tag...
return $html;
}
add_filter('get_image_tag','span_my_image_tag',10,4);
Hugo, your solution seems fine to me..doesn’t it work?
Regarding Hugo’s first code snippet, I’m having some difficulties using str_replace as an array.
Would something be possible using this example?
It works Omar
– I’ll try to catch a better solution with use of remove_filter(), apply_filter() on wp_get_attachment_link. I think that should be better and cleaner than the replace above.
Do you have any ideas, how to do this with filters?
I didn’t have a chance to delve into the wp_get_attachment_link function just yet but I assume it contains a hook to which you can assign your custom filter.
I’d like to do something similar to what both Rich and Hugo are looking for… I have a function which uses wp_get_attachment_link to display thumbnails of each attached photo, and each thumbnail is wrapped in a link to the actual full-sized image file. I’d like to add a rel attribute to each link – the same rel for each image attached to the same post, and a unique rel between the different posts – so that my jquery lightbox will automatically group the images into a separate ‘gallery’ for each post. I figure the thing that makes the most sense is to insert each post’s ID as the rel attribute.
So, for each attachment link, I need to get that attachment’s parent post ID and insert it as a rel attribute… does this make sense?
I’ve tried several ways of doing this by hooking into apply_filters in wp_get_attachment)_link, but I must be doing something wrong… keep getting parsing errors.
Any ideas on how to achieve this?
I understand your need, Jerermy, unfortunately I wasn’t able to figure out how to manipulate that a tag that wraps images yet. If you find out in the future, please share! thanks
I think I did get it figured out – though not without a lot of trial and error. You can find the code here: http://jeremybuller.com/files/my_get_attachment_image.txt (didn’t want the comments thing to garble the code)…
As you can see, it’s very similar to what you posted. Just ran into a couple of snags along the way…
Fantastic post, extremely useful! Just one question though – is there a way to make this function conditional? I.e. something along the lines of -
if (has_tag(‘my tag’)…
to apply a specific img class only to images within posts with a particular tag? I’ve dabbled with the above, but to no avail. I should point out that I’m very inexperienced, so may have put the code in the wrong place etc.
I would be very grateful for any help and again many thanks for sharing your knowledge in the first place!
Thanks Daniel. This and this posts should be able to help. The idea explained is how to get the tags of a post outside the loop. Tell me if it works for you.
Thanks Omer! I’ll let you know if I can get it to work
Your function looks pretty good, Jeremy. I haven’t tested it but if it works for you then congrats!
Do you know of a way I could do this for the post’s text? I run a blog with multiple authors, and I spend a ton of time every day fixing the same HTML codes (removing inline style tags and the divs that wordpress inserts). I would love to create a filter to automatically replace html within posts with my own rules. Would this be possible?
Hi Ashley. What you need to do is write a filter for the content that will remove inline style attributes and will look like this:
<?php
function filtered_content($content) {
$content=preg_replace(‘#(<[a-z ]*)(style=("|\’)(.*?)("|\’))([a-z ]*>)#’, ‘\\1\\6′, $content);
return $content;
}
add_filter ( ‘hook_name’, ‘your_filter’);
?>
To remove other attributes you can replace the preg_replace line with this one
$content = preg_replace(‘/(bgcolor|align|valign|size)=”[^"]*”/i’,”,$content);
In the last example, does the filter only apply to new images you upload? I’ve been using the SEO Friendly Images plugin to do the trick since I started my blog and I’m afraid that once I deactivate it, all the alt attributes will revert back to empty values.
Yes, it’ll work only on new images you upload. Regarding the SEO FI, that’s a good question but I don’t know this plugin very well. However, I bet someone has already raised up this question in WP forums so you might want to look for it there.
Omer, is it possible to only add a class to images sized “medium or large?” i just dont want to add the specific class to my thumbnail images, just those over a certain size. is that possible, how would that be written?
Hi Thomas,
If you already wrote your “get_image_tag_class” filter, delete it and use the following instead. Using regex in the filter is useful here:
function my_image_tag($html, $id , $alt, $title, $align, $size){
if($size=="thumbnail")
{
$html=preg_replace( ‘/class=(["\'])(.*?)\1/’, ‘class=""’, $html );
}
else
{
$html=preg_replace( ‘/class=(["\'])(.*?)\1/’, ‘class="post_image"’, $html );
}
return $html;
}
add_filter(‘get_image_tag’,'my_image_tag’,10,6);
This looks great, but can I ask you how to do it (change the class, alt, title….) for the images “From URL” ? I would really appreciate it. Thanks
Why would you want to change them “From URL”? Doesn’t the solution I present here suit you?
Thanks for the tip — this really helped me along.
One quick question: I just want to *add* a class to the img tag, but when I use the get_image_tag_class filter the way you have here, it seems to wipe out all the other classes (the ID-, align- and size- related classes) that are usually inserted.
How do I keep these in place, and just add one other class?
Hi jjpare, get_image_tag_class should only add a class and not remove other attributes. Can you send me your code?
The untouched tags look like this:
But after I add the function:
// Add the tilt class to images
function childtheme_image_tag_class ($class){
$tilt = (rand(1,5));
$class = ’tilt’ . $tilt;
return $class;
}
add_filter(‘get_image_tag_class’,'childtheme_image_tag_class’);
The image tag looks like this:
oops — didn’t do the img tags properly.
the original img tag looks like:
img class=”aligncenter size-large wp-image-194″ title=”Eve in the Woods” src= …etc
but after adding that function, it looks like:
img class=”tilt5″ title=”Eve in the Woods” src= …etc
Hi Omar!, your code is what I was looking for! but can you add the original code for align images to left and right please? Thank you in advance, greetings from Peru.
Hi Samantha, to add align attribute to images, you can type the following code:
function my_image_tag($html, $id , $alt, $title){
$html = str_replace(‘href=’, ‘align="left" href=’, $html);
return $html;
}
add_filter(‘get_image_tag’,'my_image_tag’,10,4);
Hi, your article is very helpful, but I have a similar question. How can you to attribute ‘rel’ on all images?. Thank you very much!
Hi Jorge, take a look at my comment to Rich – http://www.webtechwise.com/wordpress-filter-examples-changing-attributes-when-adding-images-to-posts/#comment-3020
Hey Omer, so if I wanted to change the change the “class” of each image to the same as the “alt”. would I just swap the function to say this:
function my_image_tag($html, $id , $class, $alt){
$html = str_replace(‘class=”"‘,’class=”‘.$title.’”‘,$html);
return $html;
}
add_filter(‘get_image_tag’,'my_image_tag’,10,4);
and you said this goes in functions rather than media.php right?
Hi Omer,
could you be so kind and give us a little snippet ? I can’t get this to work sadly. (I need to add the rel tag too)
Best Regards
hi, It’s a great help. Just one more question. I only need to change the atributes of thumbnails. I want them to be 70/70px, hspace 8px, and they need to be next to, but not above, the text. can you help me with the code
thanks!!!!
Hey Andrew, assigning any attribute to the image would be just the same as adding the rel attribute as described here http://www.webtechwise.com/wordpress-filter-examples-changing-attributes-when-adding-images-to-posts/#comment-3020
Thanks so much for the tip! One questions for you, I tried messing around with removing the height and width attributes and was having no luck. I control the size of the images with CSS so I don’t need the them to have a height or width declared in the HTML. Any thoughts on how to do this?
Thanks!
Hi Erik, may I ask why do you prefer to control the dimensions in the CSS?
It is considered a better method to specify dimensions of images in the HTML because this way the browser doesn’t have to calculate their size. In addition, it’s recommended to avoid resizing of images either way. If you want the image to be larger or smaller, resize it in your favorite image editor and then upload it in the desired size, instead of letting the browser resizing it (see this article http://goo.gl/zZ8Bi)
David, to put the class as the alt you can use this function:
function my_image_tag($html, $id , $alt){
$html=preg_replace( ‘/class=(["\'])(.*?)\1/’, ‘class=”‘.$alt.’”‘, $html );
return $html;
}
add_filter(‘get_image_tag’,'my_image_tag’,10,3);
Hey Omer, thanks for the quick reply. So the question is, I place this in my function.php right? I tried putting it in there, and I must be missing a bracket or something. I only have one thing in that file, so I assume I place it AFTER this:
It didn’t include my code in the previous post.
// Add support for Featured Images
if (function_exists(‘add_theme_support’)) {
add_theme_support( ‘post-thumbnails’ );
set_post_thumbnail_size( 167, 152, true ); // Normal post thumbnails
add_image_size( ‘post-thumb’, 167, 152, true ); // Normal post thumbnails
add_image_size( ‘single-post-thumbnail’, 550, 500 ); // Permalink thumbnail size
}
//Right here?
jorge and Kadir, to add a rel attribute you can use the following function and change the word whatever to whatever rel you want to add:
function my_image_tag($html, $id , $alt){
$html=str_replace( ‘src=’, ‘rel=”whatever” src=’, $html );
return $html;
}
add_filter(‘get_image_tag’,'my_image_tag’,10,3);
Omer –
I am having a weird problem with my images getting stretched disproportionately which I believe has to do with there being a height declared in the HTML. I am specifying the width in CSS because the images have to be a specific width to fit our design. I know that the images should be resized before being uploaded however the people who will be adding content to the blog may not have the image editors or the know how to produce images that are optimized for the web. So for now it makes the most sense to remove the height and width in the HTML.
Thanks!
Eric, try adding the following to your funciton.php file:
function my_image_tag($html){
$html=preg_replace( “/\width=\”(.*?)\”/is”, ”, $html );
$html=preg_replace( “/\height=\”(.*?)\”/is”, ”, $html );
return $html;
}
add_filter(‘get_image_tag’,'my_image_tag’,10,1);
Hey Omer,
I really appreciate the help! I tried adding that code and get this error:
Parse error: syntax error, unexpected ‘=’ on line 65.
In my functions.php this is line 65:
$html=preg_replace( “/\width=\”(.*?)\”/is”, ”, $html );
Thanks.
David, you can add that code to wherever you like in the functions.php file, as long as it’s not inside another function. To be on the safe side, simply paste it at the end of the file, before the closing php tag ?>
Hey Omer, sorry I’m a pest. It doesn’t seem to be working. When I past it at the end, it shows that something is missing. Here is the file if you wanted to take a look at it.
http://dl.dropbox.com/u/1042302/FD2011-Test/clean-home-working/functions.php
Here’s the error: Parse error: syntax error, unexpected T_CLASS in /home/cobradave/fromdavy.com/wordpress/wp-content/themes/clean-home/functions.php on line 12
Where is the function in that file? I don’t see it
Hey Omer, I put the function at the end of the functions file, and it doesnt look to work. In Coda, the color coding is all off, that’s why I wonder if I missed a tag somewhere. Thanks again for your help!
http://dl.dropbox.com/u/1042302/FD2011-Test/clean-home-working/functions.php
David, I think the problem is that you didn’t replace the curly quotes in my comment (I should install a plugin that automatically converts the curly quotes in my comments to regular ones). After copying my function, simply replace each single curly quote with single normal quote and the same for double quotes.
so i edited it again, I think I still did something wrong. I’m ready to give up, since I’m just bugging you at this point. Heh.
http://dl.dropbox.com/u/1042302/FD2011-Test/clean-home-working/functions.php
You’re not bugging me David, I’m happy to help. I see you still have those weird characters in your code, I have no idea how you get them
i dont know either. hehe. php is beyond me. do you think you can email me a snippet that’s correct, since it didn’t post here correctly? thanks so much for your help!
thursdavy at gmail.com
Erik, try this instead (in lines 65-66) and tell me if it works for you:
$html=preg_replace( ‘/width=\”(.*?)\”/’,”, $html )
$html=preg_replace( ‘/height=\”(.*?)\”/’,”, $html )
hhhhmmm i tried replacing those two lines and It is still returning the same error….
I finally checked this one and it worked for me:
function my_image_tag($html){
$html=preg_replace( ‘/width=(["\'])(.*?)\1/’, ”, $html );
$html=preg_replace( ‘/height=(["\'])(.*?)\1/’, ”, $html );
return $html;
}
add_filter(‘get_image_tag’,'my_image_tag’,10,1);
If it doesn’t work for you, you can send me your functions.php file
What if I want the image to not appear on the first page after using ? So, I insert an image, a text, and after the text I use but I only want the text to be visible on the first page. Thanks
Draude, so where exactly do you want to display the image?
Hi Omer,
thank you for this nice code! It’s great to get the possibility to clean up the generated code from classes and so on that are not necessary.
Thanks Bernhard
Nice to see a post where the author is actively answering questions, even a year later. Keep up the good work!
@J thanks, I do my best
To use a specific jQuery plugin I need to add the following code into de img tag.
data-href="http://www.webtechwise.com/wp-content/uploads/2010/06/rss-icon.jpg"Basically the final code should be
Is that possible to do it with a filter? Which code I should use?
Many thanks for your support
pretty nice! its good work on my blog.
now i need a TITLE tag and rel tag to change link attributes, Problem now is: how do I set the title attribute of images to the title from the media library / alt text / long description?