Fantasy E-books by PhenomenalPen

Creating WordPress Theme – Adding Thumbnail Image

Be sure you’ve finished reading the first six article about Creating WordPress Theme before reading this article. Visit the links below if you haven’t.

Support Adding Thumbnail Image in WordPress Custom Theme

Open up your favorite editor and let’s put some code. In your functions.php file add this code :


add_theme_support( 'post-thumbnails' );

If you add the code correctly you’re post editor would have this feature at the bottom. Like what this image shows:
Featured Image Support in WordPress Custom Theme
In this post, at the very top, the same image is set to be the post featured image. I always upload an image with at least 1024px width and 512px height(or 1200px by 630px). WordPress automatically adjust the size when the_post_thumbnail function is called. You can also set the image size by adding ‘thumbnail’, ‘medium’, and ‘full’ as a parameter.

Displaying Featured Image with Post Excerpt

We’ll try to add the post featured image in our index page. In this example we will just use our index.php file. Inside the loop we can add a call to the_post_thumbnail function before we call the_excerpt function. You can read Creating WordPress Theme – The Index File Loop to review the code we used in our index.php file.

Note: Instead of using the_content function, this article will use a different function to display the post excerpt. Read Creating WordPress Theme – the_excerpt or the_content Function to know why we change the codes. Now, inside the loop in your index.php file add this :


<div class="excerpt">
<?php
if ( has_post_thumbnail() ) {
      the_post_thumbnail('medium');
}
the_excerpt();
?>
</div>

In the code above we use has_post_thumbnail function to check if the post has a featured image. If an image is set, the_post_thumbnail() function is called, displaying the image. You can also assign a default featured image so that a default image is shown every time the user forgets to assign a featured image.

I put the code inside a div container to make sure some of the post details will be pushed in a new line.

e.g.


<p>Posted in <?php the_category(', '); ?> on <?php the_time('F j, Y'); ?></p>
<p><?php comments_number('No comment', '1 comment', '% comments'); ?></p>

Now your index page posts list will look like the image below :
Wordpress Custom Theme with Thumbnail in Excerpt

Well that’s it. Hope it helps. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

15 − 5 =