Latest Articles & Tutorials

Don't be stingy, Share this post with others!

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.

<img src="<?php echo get_post_meta($post->ID, 'Thumbnail',true) ?>" alt="Post Image" id="post thumb" />

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

<?php echo get_post_meta($post->ID, 'Thumbnail',true) ?>

Styling the thumbnail is very simple. Depending on where you would like your image you would float the thumbnail 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


#post_thumb 							{ float:left; padding:10px; width:225px; height:197px; }

#post_right 							{ float:left; padding:10px; width:225px; height:197px; }

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.


height:197px;
Width:225px;

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


function retrieve_my_thumbnail() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/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;
}

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)


<img src="<?php echo retrieve_my_thumbnail() ?>" alt="thumbnail"/>

That's it! Please share with your friends.

Don't be stingy, Share this post with others!

Marcell Purham

Marcell is the founder of Webdevtuts. He is also a web designer & developer who loves to design and develop websites. If you're looking for him you can find him via @webdevtuts


More posts by Marcell Purham →
, , .

6 Responses to Add Thumbnail to Post Using 2 Different Methods

  1. Pingback: wordpress « Keyurkr's Blog

Close