0
0
Wordpressframework~15 mins

Template parts in Wordpress - Deep Dive

Choose your learning style9 modes available
Overview - Template parts
What is it?
Template parts in WordPress are reusable pieces of code that help build a website's layout. They allow you to separate sections like headers, footers, or sidebars into smaller files. This makes managing and updating your site easier because you can change one part without touching the whole page. Template parts keep your theme organized and efficient.
Why it matters
Without template parts, every page would need to repeat the same code for common sections, making updates slow and error-prone. Imagine having to change the header on every page individually! Template parts solve this by letting you update one file that affects all pages using it. This saves time, reduces mistakes, and keeps your site consistent.
Where it fits
Before learning template parts, you should understand basic WordPress themes and how PHP files control page layouts. After mastering template parts, you can explore advanced theme development, including custom templates and hooks. Template parts are a key step between simple themes and professional, maintainable WordPress development.
Mental Model
Core Idea
Template parts are like building blocks that you can reuse to assemble different pages of a website efficiently.
Think of it like...
Think of template parts like LEGO bricks. Instead of building a whole new model from scratch each time, you use the same bricks to build different models quickly and consistently.
┌───────────────┐
│   Page File   │
├───────────────┤
│ ┌───────────┐ │
│ │ Header    │ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Content   │ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Footer    │ │
│ └───────────┘ │
└───────────────┘

Each box (Header, Content, Footer) is a template part reused in multiple pages.
Build-Up - 6 Steps
1
FoundationWhat Are Template Parts
🤔
Concept: Introduce the idea of breaking a theme into smaller reusable pieces.
In WordPress, a theme controls how your site looks. Instead of writing all code in one big file, you can split it into parts like header.php, footer.php, and sidebar.php. These parts are called template parts. They help keep your code clean and easy to manage.
Result
You understand that template parts are separate files included in theme pages to build the full layout.
Knowing that themes are made of smaller pieces helps you organize code better and avoid repeating yourself.
2
FoundationHow to Include Template Parts
🤔
Concept: Learn the WordPress function to insert template parts into pages.
WordPress provides get_template_part() to include template parts. For example, get_template_part('header') loads header.php. This function looks for the file and inserts its content where called. It keeps your main files simple by pulling in parts as needed.
Result
You can include header, footer, or any part in your theme files using get_template_part().
Understanding this function is key to building modular themes that are easier to update.
3
IntermediateUsing Template Part Variations
🤔Before reading on: do you think get_template_part('header', 'home') loads header.php or header-home.php? Commit to your answer.
Concept: Learn how to load different versions of a template part based on context.
You can add a second argument to get_template_part() to load specialized parts. For example, get_template_part('header', 'home') looks for header-home.php first. If it doesn't exist, it falls back to header.php. This lets you customize parts for different pages without changing the main files.
Result
You can create multiple versions of a template part and load the right one automatically.
Knowing how to use variations lets you tailor parts for specific needs while keeping fallback options.
4
IntermediatePassing Data to Template Parts
🤔Before reading on: do you think get_template_part() can pass variables directly to the included file? Commit to your answer.
Concept: Understand the limitation of get_template_part() and how to share data with template parts.
get_template_part() does not accept variables to pass data directly. To share data, you can set global variables before calling it or use functions like locate_template() with load_template(). Another modern approach is using PHP's output buffering or custom functions to pass data cleanly.
Result
You know that passing data to template parts requires extra steps beyond get_template_part().
Recognizing this limitation helps you avoid bugs and write clearer, more maintainable code.
5
AdvancedCreating Custom Template Parts
🤔Before reading on: do you think you can create template parts for any section, not just header or footer? Commit to your answer.
Concept: Learn how to create and organize your own template parts for any reusable section.
You can create template parts for any part of your theme, like a call-to-action, post summary, or navigation menu. Save these as separate PHP files and include them with get_template_part(). Organize them in folders like /template-parts/ for clarity. This modular approach scales well for large themes.
Result
You can build complex themes by composing many small template parts.
Knowing you can create any reusable part empowers you to build flexible, maintainable themes.
6
ExpertTemplate Parts and Child Themes
🤔Before reading on: do you think child themes can override template parts from the parent theme? Commit to your answer.
Concept: Understand how template parts behave with child themes and overriding rules.
When using child themes, get_template_part() first looks in the child theme folder for the requested file. If found, it loads that version, overriding the parent theme's part. This allows safe customization without changing the original theme. Knowing this helps you build child themes that extend or modify parts cleanly.
Result
You can customize template parts in child themes without touching parent files.
Understanding this override mechanism is crucial for safe theme customization and updates.
Under the Hood
get_template_part() uses locate_template() internally to search for the requested file first in the child theme directory, then in the parent theme directory. Once found, it includes the PHP file, executing its code in the current scope. This inclusion merges the template part's output into the page. The fallback system ensures the site works even if specialized parts are missing.
Why designed this way?
WordPress was designed to support child themes and modular development. The fallback search order allows safe overrides and easy customization. Separating template parts encourages code reuse and maintainability. Alternatives like copying entire files would cause duplication and harder updates, so this system balances flexibility and simplicity.
┌───────────────────────────────┐
│ get_template_part('name', 'slug') │
└───────────────┬───────────────┘
                │
                ▼
      ┌─────────────────────┐
      │ locate_template()   │
      ├─────────┬───────────┤
      │ Child   │ Parent    │
      │ Theme   │ Theme     │
      └────┬────┴────┬──────┘
           │         │
           ▼         ▼
   'name-slug.php' 'name.php'
           │         │
           └────┬────┘
                │
                ▼
          include file
                │
                ▼
       Output inserted in
       current template
Myth Busters - 4 Common Misconceptions
Quick: Does get_template_part() allow passing variables directly to the included file? Commit yes or no.
Common Belief:get_template_part() can pass variables directly to template parts like a function call.
Tap to reveal reality
Reality:get_template_part() only includes the file and does not support passing variables directly. Variables must be set globally or handled differently.
Why it matters:Assuming variables can be passed directly leads to bugs where template parts don't receive needed data, causing broken layouts or errors.
Quick: Does get_template_part('header', 'home') load header.php or header-home.php first? Commit your answer.
Common Belief:get_template_part() ignores the second argument and always loads the first file.
Tap to reveal reality
Reality:It first tries to load the file with the second argument (header-home.php), then falls back to header.php if not found.
Why it matters:Misunderstanding this fallback can cause unexpected templates to load or customization attempts to fail silently.
Quick: Can template parts be used only for headers and footers? Commit yes or no.
Common Belief:Template parts are only for standard sections like header, footer, and sidebar.
Tap to reveal reality
Reality:You can create template parts for any reusable section, like post summaries, widgets, or custom blocks.
Why it matters:Limiting template parts to standard sections restricts theme flexibility and leads to duplicated code.
Quick: Does modifying a template part in a parent theme affect child themes automatically? Commit yes or no.
Common Belief:Changing a template part in the parent theme always updates child themes using it.
Tap to reveal reality
Reality:If a child theme overrides the template part, changes in the parent do not affect the child version.
Why it matters:Not knowing this can cause confusion when updates seem ignored, leading to wasted debugging time.
Expert Zone
1
Template parts can be organized in subfolders and loaded with paths, but get_template_part() requires relative paths without file extensions.
2
Using locate_template() with load_template() allows passing variables and more control, which is useful for complex parts.
3
Child theme overrides work only if the file path and name exactly match; even small differences prevent overrides.
When NOT to use
Template parts are not ideal when you need to pass complex data or state between parts; in such cases, using custom functions or classes to render sections is better. Also, for very dynamic content, block-based themes with the WordPress block editor may be more suitable.
Production Patterns
In professional themes, template parts are used extensively to separate concerns: headers, footers, navigation, post content, and widgets. Developers often create a /template-parts/ folder to organize parts by type. Child themes override only necessary parts to customize appearance without duplicating entire templates.
Connections
Modular Programming
Template parts apply the modular programming principle to theme development.
Understanding modular programming helps grasp why breaking code into reusable parts improves maintainability and scalability.
Component-Based UI Frameworks
Template parts are similar to components in frameworks like React or Vue.
Knowing component-based UI design clarifies how template parts encapsulate layout and logic for reuse.
Manufacturing Assembly Lines
Template parts resemble assembly line stations where each station adds a part to the product.
Seeing template parts as assembly steps helps understand how complex pages are built efficiently from smaller pieces.
Common Pitfalls
#1Trying to pass variables directly to get_template_part() and expecting them to be available.
Wrong approach:get_template_part('content', null, array('post' => $post));
Correct approach:$post = get_post(); set_query_var('post', $post); get_template_part('content');
Root cause:Misunderstanding that get_template_part() does not accept variables as arguments.
#2Creating template parts with inconsistent file names or paths, causing overrides to fail.
Wrong approach:Child theme has 'template-parts/Header.php' but parent uses 'template-parts/header.php'.
Correct approach:Child theme uses exact 'template-parts/header.php' matching parent theme's file name and path.
Root cause:Ignoring case sensitivity and exact path matching required for child theme overrides.
#3Duplicating large code blocks instead of creating reusable template parts.
Wrong approach:Copy-pasting header code into every template file instead of using get_template_part('header').
Correct approach:Create header.php template part and include it with get_template_part('header') in all templates.
Root cause:Not understanding the benefits of code reuse and modular design.
Key Takeaways
Template parts break a WordPress theme into reusable pieces, making site management easier and more consistent.
The get_template_part() function includes these parts and supports variations with fallback behavior.
Passing data to template parts requires special handling since get_template_part() does not accept variables directly.
Child themes can override template parts by providing files with matching names and paths, enabling safe customization.
Using template parts effectively leads to modular, maintainable, and scalable WordPress themes.