Add Thumbnail to Post Using 2 Different Methods


Ever wanted to learn how to add a thumbnail to your Wordpress post? In this tutorial I will go over the basic fundamentals of adding a Wordpress thumbnail to your post. We will use two examples in this tutorial.

Adding the thumbnail code

Adding a Thumbnail to your Wordpress is very simple and easy. To add a Wordpress thumbnail to your post you would simpley add the code below to your index.php file.

[sourcecode language='css']
add to index.php

The code above tells Wordpress to get the thumbnail through a custom field. So to retrieve our image we would simply add the word “Thumbnail to our custom fields ”
add thumbnail

[sourcecode language='css']
ID, ‘Thumbnail’,true) ?>
[/sourcecode]

Styling the thumbnail is very simple. Depending on where you would like your image you would float the thumnail to the left to align it on the left side or float it to the right to align it on the right side.
add to index.php

[sourcecode language='css']
#post_thumb { float:left; padding:10px; width:225px; height:197px; }

#post_right { float:left; padding:10px; width:225px; height:197px; }
[/sourcecode]

Changing the width and height of the thumbnail is quite easy also. TO change the height and width you would simply go to the css and edit the height and width.

[sourcecode language='css']
height:197px;
Width:225px;
[/sourcecode]

Intermediate:

I know as a developer when I design themes for clients I try to limit the amount of code in my files to make it easier for the client to edit or get something.
In this method we will use our function.php file. Open your function.php and place this code inside

[sourcecode language='css']
function retrieve_my_thumbnail() {
global $post, $posts;
$first_img = ”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘//i’, $post->post_content, $matches);
$first_img = $matches [1] [0];

if(empty($first_img)){ //Defines a default image
$first_img = “/images/default.jpg”;
}
return $first_img;
}
[/sourcecode]

What the code above does is call your thumbnail through your functions.php file then it searches for the one line code in one of your Wordpress templates. Usually the index.php file.

add to index.php

Retrieve the image using the code below. The code below automatically retrieves an image from your post and turns it into a thumbnail ( Should be placed in your index.php template file)

[sourcecode language='css']
post, ,

Author: Marcell Purham

Hey there! My name is Marcell Purham and I am a 17 year old web developer/ designer from Chicago IL. When I'm not designing or coding things up I'm probably skateboarding, or gaming, or just being the average human. If you would like to stalk me just follow me @marcellpurham


Share


2 Responses


  1. Thanks for this Marcell! Just what I needed :) Great blog you’ve got here.

  2. thank for code. Very useful


Leave a Reply

CommentLuv Enabled