WordPress Theme Development From Scratch Part 3 : Post Loop,...

WordPress Theme Development From Scratch Part 3 : Post Loop, Post Meta, Excerpt and Featured Image

Category: WordPress   Updated by Ryan Dhungel



In this Part of WordPress theme development from scratch series, We will learn how to dynamically loop through each blog post use excerpt and also add featured image support to our theme. I hope you are following me from part 2. Currently we have all static content on our pages. Lets create some sample blog posts from the WordPress admin panel and load them dynamically on our website.

Requirements


Goals

  • Loop through each posts and display on the frontend
  • Use excerpt on blog posts
  • Dynamically load post meta content such as date and author name
  • Add featured image function to our theme


Getting Started

Lets start off by creating some sample blog posts. I will be creating 4 blog posts with some lorem epsum text that you can copy from this site. I will also create some categories, tags and assign to each posts along the way.

Now if you go to the index.php, you can see that we have <div class="col-sm-8 blog-main"> which contains all the blog posts. Within that div there is <div class="blog-post"> which contains each blog posts. As you can see, we have three  blog posts there. Now instead of those static text blocks, we want to show the posts that we just created from within the WordPress admin.

The first thing we need to do is delete the other two blog-post and keep only one.

Loop through each posts

Now let's check if there are any blog posts already created. Put this function right before the begining <div class="blog-post"> tag. While there are posts, this function will loop through each of them.

<?php if(have_posts()) : ?>
   <?php while(have_posts()) : the_post(); ?>


End this loop with the code below. Put it right after the ending </div> tag. If there are no posts then it will display the message posts not found!

<?php endwhile; ?>
   <?php else : ?>
      <?php __('Sorry, Posts not found!') ?>
   <?php endif; ?>


Now if you save and reload the page. You will not see much difference except the same old static text repeted the same number of times as your blog posts are. For example if you went ahead and created 3 sample blog posts with me earlier then you will see it repeted 3 times. Anyway let's start displaying the actual posts.

Display post title and content

Let's start off with the title. Go to the index page and find this bit of code.

<h2 class="blog-post-title">Sample blog post</h2>

Replace with the code below:


<h2 class="blog-post-title"><?php the_title(); ?></h2>

 

Just a friendly note here, I hope you are writting all the code snippets that I have put here. Don't just copy and paste, type them all and you will get much better understanding of what you are doing. It makes a big difference


Now select all your static html content and delete except this line below. Leave it there, we will come back to work on it later.

<p class="blog-post-meta">January 1, 2014 by <a href="#">Mark</a></p>


We will load the post content dynamically. Use the code below to replace your static html content.

<?php the_content(); ?>


Now I don't know about you guys but I am super excited. Go ahead and reload the page. All the posts that you created earlier through WordPress admin are there. Wow, This is cool stuff!

Use excerpt to display the post content


Our blog page looks good. But do we want the complete blog to show up on the blog lists page? Obviously not! We want to show only few lines as excerpt and show a button that says read more or something similar right? Lets do that, It's easy!

Use the code below to replace <?php the_content(); ?>

<?php the_excerpt(); ?>


Now go back to the browser and reload the page. The excerpt function is working. It's amazing, isn't it?

Create a function to control the length of the excerpt

Our excerpt length at the moment is the default length defined by WordPress. Let's create a function that will lets us control the length. That way we can make it either longer or shorter depending on our need. Using the code below we can limit our excerpt to 30 words. Open up function.php and add the code below.

// Excerpt length
function set_excerpt_length()
{
    return 30;
}
add_filter('excerpt_length', 'set_excerpt_length');


Here we added a filter called excerpt_length and supply our function name as the second parameter. Now go and reload the page to see all your blog posts excerpts are displaying with only 30 words excerpt.

Add link to single post page


Now we have a list of blog posts with short excerpt as we wanted. But we can not click anywhere to get into the single post page and read the entire post. That is not very convenient, is it? Let's add a link to the title so that we can click on the title to get to the single post page.

Head over to index.php and wrap your title <?php the_title(); ?> with the code below:

<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>


Now reload the page. All you post's title is clickable. Once you click, you get to the single post page. Awesome!

Load Published date, Author name and Author posts

Date and time

Currently we have static date and author name displayed right below the title of our blog posts. Lets make them dynamic so that the post date and author name is displayed dynamically. This is what we have at the moment:

<p class="blog-post-meta">January 1, 2014 by <a href="#">Mark</a></p>


You can delete the static date and replace with the following function:

<?php the_date(); ?>


Or you can also use the time function, Try the code below:

<?php the_time(); ?>


You can read more about the php date and time functions in the official php website to customize it further. I am using the code below which displays the date as well as the time which is pretty cool.

<?php the_time('F j, Y g:i a'); ?>


Author name, Author posts

Now lets put life to the author name and also the link so that when we click on it, we get to the page where all the blog posts from that particular author is available. Select this bit of code <a href="#">Mark</a> and replace with the code below:

<a href="<?php echo get_author_posts_url(get_the_author_meta('ID')) ?>"><?php the_author(); ?></a>


Now the author name is generated dynamically. If you click on the author name, you will get to the page with all his posts. Now your url should have such format yourtheme/author/yourname each time you click on the author name. 

Add Featured Image support


Currently our theme does not support featured image. If you go to WordPress admin and click on to add a new post or go to an existing post, you will notice that there is no place for featured image. Let's add featured image support to our theme.

Head over to functions.php and find the function below:

function my_theme_setup()
{
    // Navigation
    register_nav_menus(array(
        'primary' => __('Primary Menu')
    ));
}


This is the same function that we created earlier. All we have to do is add  add_theme_support('post-thumbnails'); to this function.

Here is what it should look like once you add the support for image:


function my_theme_setup()
{
    // Add featured image
    add_theme_support('post-thumbnails');
    // Navigation
    register_nav_menus(array(
        'primary' => __('Primary Menu')
    ));
}

Now you can go to your old posts or create a new post and add featured image to it. It's all good but you can not see the image on the front page yet. We need to do some work on our front page. Let's go for it.

Display featured image

Head over to index.php and find this line of code:

<?php the_excerpt(); ?>


We want to show the featured image right above the excerpt right? Put this line of code right above the excerpt. It will first look for the post image and display if it has one.

<?php if(has_post_thumbnail()) : ?>
   <?php the_post_thumbnail(); ?>
<?php endif; ?>


Now you can reload the page to see the images on each blog posts. But do they look too big? That's what I see. They are not fitting in. Let's wrap that in a div so that it fits well inside. Let's wrap it up.

<div class="post-thumb">
   <?php the_post_thumbnail(); ?>
</div>


Now go to your style.css and add the following code: 

.post-thumb img{
  width: 100%;
  height: auto;
  margin-bottom: 10px;
}


We added 100% width so that it takes all the width available within that div. We left the height to auto so that it don't get distorted and also added a bit of margin to the bottom. Now reload your page to see the magic. Well not really magic but it's looking pretty good with all the images right?

Just in case you missed along the way, here is what we have so far within <div class="col-sm-8 blog-main"> </div> in our index.php

<div class="col-sm-8 blog-main">
    <?php if(have_posts()) : ?>
      <?php while(have_posts()) : the_post(); ?>
        <div class="blog-post">
        <h2 class="blog-post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
          <p class="blog-post-meta"><?php the_time('F j, Y g:i a'); ?> by <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')) ?>"><?php the_author(); ?></a></p>
            <?php if(has_post_thumbnail()) : ?>
              <div class="post-thumb">
                <?php the_post_thumbnail(); ?>
              </div>
            <?php endif; ?> 
          <?php the_excerpt(); ?>
        </div><!-- /.blog-post -->
      <?php endwhile; ?>
    <?php else : ?>
      <?php __('Sorry, Posts not found!') ?>
    <?php endif; ?>
    <nav>
      <ul class="pager">
        <li><a href="#">Previous</a></li>
        <li><a href="#">Next</a></li>
      </ul>
    </nav>

  </div><!-- /.blog-main -->


and here is our function.php file so far

<?php 
// Register Custom Navigation Walker
require_once('wp_bootstrap_navwalker.php');

// Add theme support to bootstrap navigation
function my_theme_setup()
{
    // Add featured image
    add_theme_support('post-thumbnails');
    // Navigation
    register_nav_menus(array(
        'primary' => __('Primary Menu')
    ));
}
add_action('after_setup_theme', 'my_theme_setup');

// Excerpt length
function set_excerpt_length()
{
    return 30;
}
add_filter('excerpt_length', 'set_excerpt_length');


Conclusion

This is all we are going to do in this part. Here we learned about looping through each posts and publishing them. We also looked at adding meta content such as date, time and author name to the posts. And lastly we worked on adding theme support to featured image and displaying them. We did a lot of cool stuffs.

In Part 4, We will learn about single post, single page and comments functions. Lots of cool stuffs ahead.

Stay in touch, Leave your comments below and use our forum for any difficulty you encounter along the way.

Download source code from github 



Back to articles