
This tutorial will explain how to add images to your posts using WordPress custom fields. It is the third part of the Using WordPress Custom Fields Series. This tutorial assumes you at least know what XHTML, PHP, CSS, and WordPress are. Plus, you should know how to input a custom field “Key” and “Value” and upload images.
The example I’m basing this tutorial off of is Dosh Dosh. If you notice, he adds an avatar-sized image to each post. I don’t know whether he uses a technique like I’m about to explain or adds each image to the “Post” box.
Why use custom fields to add images to posts?
There are two main reasons for this. Typically, when a blogger adds an image to a post, he or she will simply upload the photo and add the picture in the posting textarea.
- You can display images when using excerpts.
- You can pull the image out from just about anywhere and use it how you like.
Most WordPress theme archive, category, and search templates display post excerpts, and even some home pages. Why not display a custom image for each post? This technique will allow you to do that.
If you take a look at my WordPress Themes page, you can see how I pull an image out of a custom field. Of course, I created a plugin with some added features for that particular page. But, it shows you how information can be pulled out of custom fields to be used elsewhere on the blog.
Upload images and create Keys and Values:
The first thing you need to do is upload an image. For the sake of this tutorial, I will assume these images are thumbnailed-sized, such as ones that you might see on a message board or at Dosh Dosh. You can, of course, do as you like when it comes to sizing your images.
Now, create a Key named “Thumbnail.” Give it a Value of the URL of the image you uploaded (ex: /wp-content/uploads/image.gif).
Create a key named “Thumbnail Class.” Give it a Value of “thumbnail-class” or anything that you can use to style in your stylesheet (style.css).
You can also create alt text for your image. This is optional. Create a Key named “Thumbnail Alt” with a Value of “Describe your image.” If you don’t do this, the alt text will default to the post title.
Now, for the code:
You can use this code in any of your templates (index.php, single.php, category.php, archive.php, etc.). Open one of those files in your text editor of choice (I’m editing index.php in Notepad).
After:
if(have_posts()) : while(have_posts()) : the_post();
Add this:
// check for thumbnail
$thumb = get_post_meta($post->ID, 'Thumbnail', $single = true);
// check for thumbnail class
$thumb_class = get_post_meta($post->ID, 'Thumbnail Class', $single = true);
// check for thumbnail alt text
$thumb_alt = get_post_meta($post->ID, 'Thumbnail Alt', $single = true);
Basically, this just retrieves your custom field information for each post that will be displayed by the loop. When it retrieves the custom field Key and Value, it assigns it to a PHP variable. This is important because it’ll make the coding later cleaner and we only have to retrieve the information once for each post. (Also note that this is the technique I’ll use on later tutorials, unless I come up with an even better way to accomplish this.)
Before (in the same file):
<?php the_content(); ?>
or
<?php the_excerpt(); ?>
Add this code:
<?php // if there's a thumbnail
if($thumb !== '') { ?>
<p>
<img src="<?php echo $thumb; ?>"
class="<?php if($thumb_class !== '') { echo $thumb_class; } else { echo "left"; } ?>"
alt="<?php if($thumb_alt !== '') { echo $thumb_alt; } else { echo the_title(); } ?>"
/>
</p>
<?php } // end if statement
// if there's not a thumbnail
else { echo ''; } ?>
This code outputs the image right before your content is displayed. Pretty simple, huh? You can obviously add other things like width and height using custom fields or set a width and height for all images. What I will show you next is how to do this with your “thumbnail-class” instead.
Open style.css file from your theme folder and add this code:
.thumbnail-class {
float: left;
width: 100px;
height: 100px;
margin: 0 15px 0 0;
}
.left {
float: left;
margin: 0 15px 0 0;
}
The class “left” is the default in case you forget to input a “Thumbnail Class” custom field Key. Obviously, how to style your image is up to you. Play around with it, have some fun, and see what you can come up with. You can also do away with the entire “Thumbnail Class” custom field and just input the class in the XHTML. I prefer to leave “Thumbnail Class” open, in case I want to style or align individual thumbnails differently.
That’s pretty much it. You can do a lot with this. For example:
- Add a link around the displayed thumbnail to a larger image, another page, or the single.php page.
- List posts by just their image.
- Creat kick-ass archive and search pages.
As I’ve said before regarding custom fields, their only limit is your imagination. Follow this tutorial series by subscribing to the feed. If you have anything you would like to see done and think it might be possible with custom fields, let me know because I’m always looking for more things to play around with.
Hey, cool! Neat tip, thanks for sharing.
Thanks Travis. This is just as much a learning experience for me as it might be for you or other readers. WordPress has been out for too long, we need to figure out what kinds of things we can do with these custom fields.
Hi there,
Thanks for the tutorial! Can I ask for help?
I can display the image in the article with your method but still not in the frontpage like your example. It works well when I “enter” a post thought.
I’m testing it on the default template with wp 2.3.1
Do you have any idea ?
Blackbelt, I see you’ve got it working. But, for future reference for others: you must change this in any template you want to use it, like single.php or home.php.
Justin,
Thanks for all your work. I have have a question about how to extend this technique. I understand about how to call the photo before the_content,etc. This way the photo always shows at the top of the post. How about if you want the photo to always appear on the same line as, let’s say, the 3rd paragraph. I’ve been experimenting with the technique described here: See post but can’t get it work. Any Iseas? Thanks again.
Jvsn, I think we should be able to get this to work. Just give me a little time, and I’ll do a little experimenting of my own. This looks like a great way to extend this tutorial series too.
Thanks for this, Justin. I may use this with my redesign!
Thanks Justin,
I’m still trying as well.
Jvsn, this looks simple enough. Just replace
the_content();with this:Make sure to put the image code you’re using in the // Place your image code here area, which would be the code you use right before the content.
I just tested this, so it should work fine.
Thanks Justin. With your help, I was able to figure out what I was doing wrong and now have the solution working. I’ll send a link when the site is up and running so you can see how I implemented this technique. Thanks again for the excellent tutorials. They have been very helpful. Best.
I’ve got this code working except that I don’t want to upload images, I want to link to external images (an image on another website I own), that is linkable to an external link. So would be the final output, is there some way I can do this? Thanks!
Jvsvn, that’s great. I’d love to see how you’re using it.
Marcy, you can definitely do that. Just use the image URL as the Value of your custom field Key of “Image.”
Question, I want it to appear in my sidebar, so how would I manipulate this code for the ‘Get Posts’ loop? Thanks!
Erika, do you want to add only the images in the sidebar? Also, is it necessary to use “
get_posts(),” or can we use a different way to pull the posts from the database?This might be a good reason to write another tutorial. I’ll work on it as soon as I get a chance. It shouldn’t be too much different though.
1. Like jvsvn had mentioned earlier, I am attempting to place my images in posts other than the very beginning. Will I have to just insert them accordingly in the content?
2. Meanwhile, I would like to be able to display a thumbnail image on the mainpage that is not displayed on the single page. I have edited the single.php page to NOT include thumbnails, but not sure if the is correct.
You’ll see your template in action (sort of) on my site.
TR
I don’t really help people that use my themes but remove the credit link, which is a violation of the license.
hello justin,
i installed your theme localy to get in touch with those features like customfields and the video section.
i think i can handle this now. my question to you is, how can i get the tabs in the sidebar to work?
do i have to add something, create new pages for the comments?
the sidebar is shown correct, but the links in the tabs dont work
would be nice if you can answer me whenever your time allows you
r.s.
You should ask this question on the page of the theme you’re referring to. Also, you need to tell me exactly what problems you’re having and, if possible, give me a link to your site.
[...] I couldn’t do half of the things he wanted me to do. But then came custom fields. Using the same tutorial I used for adding photos to posts, I reworked the code over and over again until I added a ton of features that you would have never [...]
Oh nifty. I wanna use this for my upcoming portfolio! Thanks so much!
I’d like to include thumbnails with the “previous” and “next” links on permalink pages. For example, right now I’m displaying what comes next and previous:
<?php previous_post_link(’PREVIOUS EPISODE: %link’) ?>
<?php next_post_link(’NEXT EPISODE: %link’) ?>
How can I display their corresponding thumbs?
[...] WordPress Custom Fields Adding Images To Posts: Using avatar-sized images like DoshDosh.com (tags: wordpress howto programming) [...]
my thumbnail image wont float left. it stays above the entry text no matter what i do.
[...] do the images you use custom fields.WordPress Custom Fields: Adding Images To Posts: Using avatar-sized images like DoshDosh.com __________________ Blog | Portfolio | [...]
Justin,
Do you know how to get the custom images fields to show up in an RSS feed? I am using the custom fields for thumbnails.. but I’d like the thumbs to appear in the RSS feed. Is that possible?
Thanks,
Charles
Hi Justin, How to add the URL Patch of the images? paste manually? from the URL after Upload? or it’s will automatically generated when we Upload new images?
[...] (mit Hilfe der “Custom Fields”) und auch die Sache mit den Teaserbildern wird mit diesem Tutorial (englisch) und den “Custom Fields” auf einmal ganz [...]
I have tried to use this thing for your visionary theme, but am going nuts trying to figure out why it shows the thumbnail image and the large image in my post when i use this field.
I did hat you said in the directions. I cant seem to figure out whats screwed up here.
Thanks for this very helpful piece of code! I was looking for a plugin like this exactly. It really adds structure to the thumbnails with each post on my category pages.
I have a question: I like to use square thumbnails (resized to 100×100px) for all my post excerpts. Is there a way that I can also crop the image with your code, so a rectangled picture is not distorted when I resize it to a square format?
(I’m no CSS or PHP expert so this might be a dumb question)
I want to ask.com and searched on Wordpress and “create a link to an image from custom fields.” Your tutorial came up right at the top of the list, and gave me exactly the information I needed. I’m using it slightly differently. I’ve created a category page specifically for a given category. In the “page” for each movie review, the “poster” for the movie is aligned on the right. But in the category listing, I wanted the image aligned on the left with just the title and excerpt.
In the past, I would paste the entire link with size, border, and alignment info into the custom field. This was, to say the least, cumbersome. By using ideas gathered here, now all I need is the url to the image…the rest of the sizing and alignment info is now part of the code for that particular category page.
Thank you for taking the time to provide this.
Hi! Thanks for this great post
I adapted it to get videos. The problem I have is the following:
I use this code:
The only problem I have is that I can’t get the SOME RANDOM STUFF to be displayed.
Do you know what I could possibly be doing wrong?
[...] With the above technique, you can do some pretty fancy stuff. For example, you can only retrieve posts with custom images for a nice magazine effect. [...]
[...] Foloseam deja metoda descrisă aici. [...]
Thanks for this, Justin.
Just one quick question..
how can I add a border to the code without messing everything up using just one simple css line.
Thanks
Jamie
Thank so much, I had it down, but I was just a little confused about the php key; ie:
$thumb = get_post_meta($post->ID, 'Thumbnail'I am doing this for my personal blog: The Frosty
Have you seen this plugin – http://www.Mediatricks.biz/demo. I just added it to my blog and it’s a WONDERFUL to not have to keep adding those custom fields anymore.
I have been using custom fields for image display on my blog for a while and it seems to be becoming really popular now with new theme developers like Revolution, Unstandard, Mimbo etc. but it does add a serious amount of time to every post having to not only tag the right urls in the custom fileds but uploading correctly sized images for display in the theme. If anyone is serious about using custom fields and linked images in their theme check out the Mediatricks Viva Thumbs plugin. I am only recommending his because I got it and it really works! Life saver – trust me.
This is a great article!
How would I use this to display a list of posts, showing just their title and post image?
Jenny
Please do use it for your portfolio.
You’d have to check your entry CSS. It probably has something preventing it from floating next to the image.
Sean
I think there’s a way to do that in the WordPress Codex somewhere.
Charles
Check out the custom fields for feeds plugin.
Jauhari
You just add the URL to whatever image you want to use. It doesn’t have to be something you uploaded.
JC
I have support forums for my themes.
Yvonne
You can’t just crop images with basic code. It’d take a much, much larger script to get that done.
B John M
No problem. This is exactly how what this type of tutorial is supposed to be used for.
Isabelle
It looks like your code got cut off, at least some of it. Stop by the forums, and we’ll work it out. I also have a tutorial on doing this with videos I can point you to.
aone
You’re welcome
Jamie
Use your thumbnail class to do this:
border: 1px solid #000;Austin
What do you mean you’re confused about the PHP key?
John
I’ve got a similar script coming out soon too. Of course, mine will be free.
Brooke
Stop by the forums here, and explain what you’re trying to do in a bit more detail. We’ll work out a solution for you.
[...] go to Justin Tadlock, where I got the ideea [...]
Will come in very handy, but I ran into a small issue. Everyone of my post start off with and they all are broken where I want them.
I want to insert my img in that same starting and for the life of me I can’t figure out how. Here is what I am currently working with.
the_content('Continue Reading');Maybe too tired to figure out the explode for it.
hey man, thanks for this, this was a milestone design issue i just over came thanks to you.
[...] WordPress Custom Fields: Adding Images To Posts [...]
Great article, I’ve implemented it in my theme and it works perfect for the first article posted, but when I post another article in the same category it still displays the first posts image or custom field value. Any ideas on why this is happening?
[...] go to Justin Tadlock, where I got the ideea from. [ Download [...]
[...] archives, for the more recent posts, you will see little pictures alongside the article summaries. Here’s how I did it. Here’s an example of the results of 1 and [...]
Dear Justin. Thanks for this tutorial. One question. I want to use custom fields for displaying thumbs. But also, I want to have a default image placed somewhere inside my theme’s images folder which will be displayed when no image is attached to the post. How do I do it? I would appreciate if you could show me full code. Thanks in advance.
Hrmmm…Could this be the answer: http://justintadlock.com/archives/2008/05/27/get-the-image-wordpress-plugin
Although, I would prefer a few lines of code which I could place inside my theme’s template so I don’t have to worry about upgrading your plugin. Thanks.
Thanks for this.
I fear I am too….non tech to be able to do this. I have had much challenges with customizing my WP site. I paid someone $200 and ended up redeveloping it again myself. I know have someone contracted to redo my content and customize my theme. Unfortunately this person is not ’steppin up’ and I am finding myself holding hands through the process, which tells me I should just get better at doing it myself.
That said, I am learning that if it involves editing codes, for me, it is something to think hard about implimenting. However, the script mentioned above by John that you have suggested you are working on too is of interest. I get the impression that this sort of script takes a bit more of the backend tech stuff out of the equation.
Please let me know when you have your script ready.
Cheers,
Jeromy
[...] Custom Fields are data fields that are not part of the core Wordpress installation but that you define yourself. A custom field is attached to a post or a page and can be used to store any extra info that Wordpress or plugins dont handle. For restillmexico.se I use it to store the URL or the images for each page, as well as the attribution of the images etc (a trick from WordPress Custom Fields: Adding Images To Posts). [...]
[...] WordPress Custom Fields: Adding Images To Posts- This tutorial will explain how to add images to your posts using WordPress custom fields. [...]
[...] For a more advanced alternative to this method, check out Justin Tadlock’s method. [...]
You saved my life with this tutorial. Thank you so much!
This is come quality stuff, thank you!
Hi Justin! Thanks a lot for this, it was the only tutorial working.
Only one small problem .. when I put it in archives.php and I then click for example “archive september 2008″ it shows the thumbnail of the latest post I did with every article. So the same thumbnail over and over again in every post. What is going wrong here?
Thanks a lot
[...] more information on using custom fields, check out “WordPress Custom Fields” by Justin Tadlock; and you may also be interested in “5 Quick Ways To Enhance Your WordPress Theme” [...]
I came across your tutorial today, read through it, and it seems like a great resource. I thought, this is really well explained and should be easy to implement.
I am developing locally, so I can’t link to an external resource. I added the custom fields, but the if statement is finding that the $image variable is empty set, when I have entered an image path in my ‘Thumbnail’ variable. (/images/test_thumb.jpg) I put an error message in the echo for the else and that is what I am getting, and when I do an echo on the $image variable, nothing displays.
Will the conditional find the variable to be empty set if the image link tag can’t find the image?
This seems like something simple and stupid on my part. Do you know right off the top of your head what might be my problem? Could it be a plugin conflict? I assume this information will work with WP 2.6 and above.
If you have time….if you don’t, I understand.
[...] WordPress Custom Fields: Adding Images To Posts [...]
hi!
while searching for some stuff on custom fields i found your tutorial and i understood quite a few things .
Thanks, great!
One question though: the custom fields interface is a bit basic … i cannot specify what type of field i need to use.
I did find some pugins that modifify the interface and alowa that but none of them does what i need: i need a file type field.
Do you have any ideeas?
thanks
adrian
rafy
If you need a file type field, you might be better off working with image attachments instead.
But, the current custom field interface is all you’ll ever need for images. You can use a PHP function to find the image extension if needed.
Hello Justin,
i am trying to use more thumbnails for my post by using your code. I have no knowledge so i am just experimenting.
So far i have managed to make 4 thumbnails appear to my post by using 4 custom fields. ( basically i wanted to align three smaller thumbs next to the main thumb and i did but….)
what happens is that although i am using 4 different custom fields all images are pulled from the last one.
These are the changes i made, i guess there is a workaround for it so could you please help me?
Thanks so much in advance!
wordy
You need to stop by my support forums if you need help.
OMG thank you so much for posting this… XD
[...] Wordpress 提供的自定义域功能强大,需要慢慢学习,这里有一篇资料可以参考。 [...]
Thanks for this! Really helped me ALOT!
Hi!
Awesome tutorial, this is really usefull
I have a problem though, on http://www.speedrevision.se/ (extremely experimental stage) i use your code to make the thumbnail appears, the problem is that is only shows the one i upload latest, shouldnt it be 3 different thumbnails since i used a different image link on every post?
Hehe sorry, i´ve had a querry post that messed it up, it works fine now, thanks for all your work in this site
[...] Using wordpress custom fields. [...]
Thx Justin. I really loved the tutorial. Easy to implement. i wanna ask something though
I succesfuly add the custom fields and stuff but if i dont add normal post image after more tag, i can see both custom field image and post image on the main page.
How can i make normal images to shown only on the single page.
(sorry i accidently post this comment on other post)
Thank you so much for sharing!!!!
It helped so much!!!
(My knowledge is limited when it comes to php and all)
Arigatou!! ^__^
Hello Justin,
Thanks for this great tutorial, it works great! But can you tell me how i can place a “standard” thumbnail when i have no image…
Hello Justin,
I forget to ask of there is a tutorial for:
Add a link around the displayed thumbnail to a larger image, another page, or the single.php page.
Have a nice evening!
hi,may I ask, why my wordpress can’t display every single post a view value at beside the post?
this is my web :http://thepplway.createbloggers.com
thanks
Hi – I followed your instructions and the image appeared straightaway – but I have one problem -
As I’ve created other types of custom fields, and have put within the loop of the index.php template I now get the key (Thumbnail) and the value (path to image) printed underneath my post! Any way of not getting that printed out?
Thanks of the tutorial whatever the case!
Amendment to my question above (I included some php but it didn’t print -
As I’ve created other types of custom fields, and have put within the loop of the index.php template I now get the key (Thumbnail) and the value (path to image) printed underneath my post! Any way of not getting that printed out?
thanks!
Thanks for the tutorial. Is there a way to get several thumbs in one post? My code looks like this:
I haven’t figured it out yet…
[...] a neat tutorial at justintadlock.com that shows how to use custom fields to add images to posts. I modified the instructions a bit for [...]
Thanks a lot for this one, really helped me and kick ass explenation!
What could be cool and pretty usefull for designers if you want to showcase your references is a thumbnail link. Now visitors can click on the image and get linked to a specific image file
Thank you!
is it possible ti use the custom fields to show the Next / Previous image navigation?
[...] WordPress Custom Fields: Adding Images to Posts [...]
[...] the original post: Showing thumbnails with WordPress custom fields Share and [...]
[...] WordPress Custom Fields: Adding Images To Posts: Using avatar-sized images like DoshDosh.com [...]