0
0
WordpressHow-ToBeginner · 3 min read

How to Use Template Parts in WordPress for Modular Themes

In WordPress, use get_template_part() to include reusable template parts like headers, footers, or content blocks in your theme files. This function loads a template part from your theme folder, helping you keep your code organized and modular.
📐

Syntax

The get_template_part() function loads a template part file from your theme. It takes two parameters:

  • $slug: The base filename of the template part (required).
  • $name: An optional specialized part to load (optional).

WordPress looks for {$slug}-{$name}.php first, then falls back to {$slug}.php.

php
get_template_part( string $slug, string $name = null );
💻

Example

This example shows how to include a header template part named header-site.php inside your main template file.

php
<?php
// In your theme's index.php or page.php
get_template_part('header', 'site');
?>
Output
The content of header-site.php is included here, rendering the site header section.
⚠️

Common Pitfalls

Common mistakes include:

  • Not naming template parts correctly, causing WordPress to fail loading the file.
  • Forgetting to place template parts in the theme folder or subfolders.
  • Using include or require instead of get_template_part(), which bypasses WordPress template hierarchy and filters.
php
<?php
// Wrong way - direct include (not recommended)
include 'template-parts/header-site.php';

// Right way - use get_template_part()
get_template_part('template-parts/header', 'site');
?>
📊

Quick Reference

FunctionDescription
get_template_part('slug')Loads slug.php from theme folder
get_template_part('slug', 'name')Loads slug-name.php if exists, else slug.php
Template parts folderCommonly stored in /template-parts/ for organization
Use in theme filesCall inside theme PHP files to insert reusable sections

Key Takeaways

Use get_template_part() to include reusable theme sections cleanly and modularly.
Name your template parts clearly and place them in your theme folder or a subfolder like /template-parts/.
Avoid direct PHP includes; get_template_part() respects WordPress template hierarchy and filters.
You can load specialized parts by passing a second parameter to get_template_part().
Template parts help keep your theme code organized and easier to maintain.