WP: Create A Page Template

Let’s say I want to list down all the posts tagged with a keyword on a page. I could achieve this by creating something called a Page Template.

To do so, I’m going to my theme folder which is located at wp-content > themes > twenty-seventeen and then I’ll create a new page there using this rule: page-templatename.

Basic Page Template

The new page that I created is page-onedemo.php and it has the following content –

<?php 
/*
Template Name: One Demo Template
*/
?>
 
<p> TEST PAGE </p>

I’m now going to create a new page inside admin dashboard > pages and select template as One Demo Template as follows:

Opening this page in the browser gives this result:

Page Template With Posts

It doesn’t do much but it’s a good start. Now I’m going to show a list of posts using the following code:

<?php 
/*
Template Name: One Demo Template
*/
get_header(); ?>
 
<?php 	$myposts = get_posts();
		foreach ($myposts as $post): ?>
		<li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php 	endforeach; ?>
 
<?php get_footer(); ?>

To break it down, here’s what it does (step by step):

  • Get posts and store inside $myposts
  • Then loop through $myposts and fetch each post as $post
  • Fetch time, link and title of $post
  • End for loop

And here’s the result of that:

With Header And Footer

To beautify this result, I can look into page.php inside my current theme’s folder and make adjustments as follows:

<?php 
/*
Template Name: One Demo Template
*/
get_header(); ?>
 
<div class="wrap">
	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">
 
<?php 	$myposts = get_posts();
		foreach ($myposts as $post): ?>
		<li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php 	endforeach; ?>
 
		</main><!-- #main -->
	</div><!-- #primary -->
</div><!-- .wrap -->
 
<?php get_footer(); ?>

This gets me header and footer and beautifies the result as follows:

That’s all in this post! 🙂

Leave a comment