0
0
Wordpressframework~5 mins

Template parts in Wordpress

Choose your learning style9 modes available
Introduction

Template parts help you reuse pieces of your website design easily. They keep your code clean and organized.

You want to show the same header on many pages.
You need a footer that looks the same everywhere.
You want to reuse a sidebar with widgets on multiple pages.
You want to separate your page layout into smaller, manageable pieces.
You want to update one part and have it change everywhere automatically.
Syntax
Wordpress
<?php get_template_part( 'slug', 'name' ); ?>

slug is the main part of the template file name.

name is optional and adds a specific variation.

Examples
Includes the header.php file.
Wordpress
<?php get_template_part( 'header' ); ?>
Includes the content-single.php file.
Wordpress
<?php get_template_part( 'content', 'single' ); ?>
Includes the sidebar-blog.php file.
Wordpress
<?php get_template_part( 'sidebar', 'blog' ); ?>
Sample Program

This example shows how to load a header, a content template part for the homepage, and a footer. The content-home.php file holds the homepage content. This keeps your main file clean and easy to update.

Wordpress
<?php
// In your theme's index.php file
get_header();

// Load the main content template part
get_template_part( 'content', 'home' );

get_footer();

// content-home.php
// This file contains the main content for the homepage
?>
<section>
  <h1>Welcome to My Website</h1>
  <p>This is the homepage content loaded from a template part.</p>
</section>
OutputSuccess
Important Notes

If the specified template part file does not exist, WordPress will not show an error but will skip it.

Use template parts to keep your theme organized and easier to maintain.

Summary

Template parts let you reuse pieces of your theme easily.

They keep your code clean and organized.

Use get_template_part() with a slug and optional name to include parts.