Template Parts

After all this thing, when you visit your website there is only a blank page. In this lecture, we will discuss “WordPress Page Hierarchy”, Page templates, and Template parts. According to wordpress, every page route in a page.php file. It means if you create a page it’s automatically got page.php file and shows data on the front.

Page.php
According to our theme, we created page.php. When you type some in it. it shows on the front page. Copy below code and paste on page.php file

<?php get_header(); ?>

<h1><?php the_title(); ?></h1>

<?php get_footer(); ?>

 

This is the first time we add a template part to our custom WordPress theme. The template part is a block of code that we use specific code multiple times. We add a section in page.php to get content from wordpress theme editor.

Create a folder for all Template Parts:
create a folder for the template part with the name templates and create section-content.php file.

Template Part

Now, We have a section setup, we need to go into our section and then put code to be able to pull the content for that specific page from the database.

Add worpdress standard loop:

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

    <?php the_content(); ?>

<?php endwhile; else: endif; ?>

 

Add this code in page.php and other pages by using wordpress pre-build helper function get_template_part(),

<?php get_template_part( 'content' );           // if filename in single word (content.php) ?>
<?php get_template_part( 'section', 'content' ); // if filename in two words (section-content.php) ?>

 

if you follow our custom theme development course follow below code to get_template_part().

<?php 
    get_template_part('templates/section','content');
?>

 

Now, Create pages, and when visiting that page you will see the dynamic content will appear in front.

Home Page

Front view, When you visit page.

Set Static Home Page

Visit wordpress dashboard and navigate to Settings -> Reading, and you will see “Your homepage displays” option there. Just select your page and save changes.

Reading Setting

#BeginCodeStuffer

Related Theme Developments