Create a Space theme for WordPress – 2021 – Part 4, Template parts

Create an includes folder and add template parts

To make the theme more manageable, create a folder in the spacetheme folder named includes. this will contain the template parts for various pages. A template part is loaded into a page template using the function get_template_part(). A template part is just a block of custom content.

Add the template part function and your front-page.php file should now look as below. This function has two parameters the first is the path to the file and the prefix, in this case, section. The second is the name of the template part.

<?php get_header();?>
    <section class="page-wrap">
        <div class="container">
        <?php the_title()?>
        <?php get_template_part('includes/section', 'content')?>
        </div>
    </section>
<?php get_footer();?>

Create a template part. The WordPress Loop

In the includes, folder create a file named section-content.php. This file uses the WordPress loop to add the content to the page. First, the if have posts() … function checks to see if there is any content. If this evaluates to true The while loop will run.

Inside the loop the_content() function loads the page content. The last line ends the while loop or if statement, depending on which evalutes to true.

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

<?php the_content();?>

<?php endwhile; else: endif; ?>

Add content to the page.php file

At the moment there is no content in the page.php file. This is the file used by all pages except the Home page. Just copy and paste the code from front-page.php. Now all pages should work.

Template files for pages

A page can have a different template assigned to it. This is done under page attributes in the editor. Next, we create a contact us template file. This will have two columns instead of one.

Create a file named template-contactus.php, the template prefix lets WordPress know it is a template file. At the top add a comment as shown below. This code will add Contact us as an available template in the editor.

<?php
/*
Template Name: Contact us
*/
?>

Finally add the code below, under the comment. Bootsrap is used to create two coulumns.

<?php get_header();?>
<section class="page-wrap">
<div class="container">
<h1><?php the_title()?></h1>

 <div class="row">
  <div class="col-lg-6">
    <p> This is the left column </p>
  </div>
  <div class="col-lg-6">
   <?php get_template_part('includes/section', 'content')?>
  </div>
 </div>

</div>
</section>
<?php get_footer();?>

That completes this tutorial, next we add some navigation.