Become Wordpress Professional - Your Ultimate Wordpress Guide

Thursday, 12 September 2013

How to Create Custom Blog Page template in Wordpress

Method of creating a blog template page in WordPress is same for creating any type of template page in WordPress but a minor variation in terms of coding to add more functions to the template page. In this tutorial, we are going to learn how to create a blog template in WordPress and to display posts on that blog template page.

How to add template page file

First of all create a file with the name "blog.php" and then add this file to your theme directory

How to create a custom blog page template

After you have added "blog.php" to your theme directory you have to add following code at the top of the blog template page to let WordPress know that this is a special kind of page:
<?php

/*
Template Name: Blog Homepage
*/

?>

How to display posts on blog page template

Now that we have made the page template, all we need to do is run a loop that will fetch the latest posts along with their titles and content and display on the blog page.
Before we run the loop we need to tell wordpress that how many number of posts do we want to display, for that we need to call the query_posts which is a built in function of wordpress:
<?php query_posts( array( 'posts_per_page' => 5 ) ); ?>

Next we need to start out loop that will fetch the title and content of the 5 posts.
<?php if(have_posts()): while(have_posts()): the_post(); ?>
Now that our loop has been started, we can render the title and content of the posts and the read more link that points to the full post.

<h1 class="post-heading"><?php the_title(); ?></h1>
<div class="content"><?php the_excerpt(); ?></div>
<a href="<?php the_permalink(); ?>">Read More</a>
Now we need to end our loops, the following code will end our loops:

<?php endwhile; endif; ?>

Now we can call our sidebar if there is any and then the footer:

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Note that we have wrapped the title and the excerpt in heading tag and a division tag respectively, and given each a class which can be styled using style.css, the Read More link can also be styled in a same way.

Click Here to see all the code combined.

0 comments:

Post a Comment

Please Avoid Spamming. Comments will be moderated before they are published.