Can You Customize Template Parts Per Page Template in WordPress? Yes—Here’s How

Yes, you can absolutely customize template parts per page template in WordPress! This is a common and powerful way to create unique layouts and content for different pages on your site.

Below, you’ll find a detailed guide on how to achieve this, including different methods and code examples.

Customizing WordPress Template Parts Per Page Template

WordPress’s templating system is incredibly flexible, allowing you to reuse sections of code (template parts) across your site. However, there are often scenarios where you need a specific header, footer, sidebar, or other content block to appear only on certain pages or page templates. This guide will show you how to achieve that customization.

What are Template Parts?

In WordPress, template parts are small, reusable PHP files that contain snippets of code for specific sections of your website. Common examples include:

  • header.php: Contains the site’s header, navigation, and opening <body> and <html> tags.
  • footer.php: Contains the site’s footer, closing <body> and <html> tags, and scripts.
  • sidebar.php: Contains the sidebar content.
  • content.php, content-page.php, content-single.php: Used for displaying post or page content.

These parts are typically included in your main theme files (like page.php, single.php, index.php) using functions like get_header(), get_footer(), get_sidebar(), or get_template_part().

Why Customize Template Parts Per Page?

Customizing template parts per page allows you to:

  • Create unique landing pages: A landing page might need a simplified header or no footer.
  • Implement special layouts: A portfolio page might have a unique sidebar or content structure.
  • Show different navigation menus: Certain sections of your site might require different navigation options.
  • Display specific widgets: You might want different widgets to appear on your blog page versus your contact page.

Methods for Customizing Template Parts

There are several effective ways to customize template parts based on the page template or specific page.

Method 1: Using Conditional Logic within Template Parts

This method involves adding conditional statements directly within your existing template part files (e.g., header.php, footer.php, sidebar.php) or within the main page template file that calls them.

Example Scenario: You want a different header logo or navigation menu on your “About Us” page (which has a page ID of 5).

Steps:

  1. Identify the page: Use WordPress conditional tags like is_page(), is_singular(), is_front_page(), etc.
  2. Modify the template part: Open the relevant template part file (e.g., header.php).

Code Example (in header.php):

<!-- header.php -->
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>

    <header id="masthead" class="site-header">
        <div class="site-branding">
            <?php
            // Check if it's the 'About Us' page (ID: 5)
            if ( is_page(5) ) {
                echo '<a href="' . esc_url( home_url( '/' ) ) . '" rel="home">';
                echo '<img src="' . esc_url( get_template_directory_uri() . '/images/about-logo.png' ) . '" alt="About Us Logo">';
                echo '</a>';
            } else {
                echo '<a href="' . esc_url( home_url( '/' ) ) . '" rel="home">';
                echo '<img src="' . esc_url( get_template_directory_uri() . '/images/default-logo.png' ) . '" alt="Default Logo">';
                echo '</a>';
            }
            ?>
        </div><!-- .site-branding -->

        <nav id="site-navigation" class="main-navigation">
            <?php
            // Check if it's the 'About Us' page (ID: 5) to load a different menu
            if ( is_page(5) ) {
                wp_nav_menu( array( 'theme_location' => 'about-menu', 'menu_id' => 'about-primary-menu' ) );
            } else {
                wp_nav_menu( array( 'theme_location' => 'primary-menu', 'menu_id' => 'primary-menu' ) );
            }
            ?>
        </nav><!-- #site-navigation -->
    </header><!-- #masthead -->

    <div id="content" class="site-content">

Pros: Simple for minor variations. Cons: Can make template files cluttered if you have many conditions.

Method 2: Creating Custom Page Templates

This is the most common and recommended method for significant layout changes. You create entirely new page templates that include different template parts or variations of them.

Example Scenario: You want a “Full Width” page template that doesn’t include a sidebar, and a “Contact Page” template with a unique contact form section.

Steps:

  1. Create a new PHP file in your theme’s root directory (or a subfolder like page-templates/).
  2. Add the Template Name comment at the top of the file.
  3. Include desired template parts within this new file.

Code Example (for a page-full-width.php template):

<?php
/**
 * Template Name: Full Width Page
 * Template Post Type: page
 */

get_header(); // Includes the standard header

?>

<div id="primary" class="content-area full-width-content">
    <main id="main" class="site-main">

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

            // This will load content-page.php or content.php by default
            // You could also load a specific content part like:
            // get_template_part( 'template-parts/content', 'full-width-page' );
            get_template_part( 'template-parts/content', 'page' );

            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;

        endwhile; // End of the loop.
        ?>

    </main><!-- #main -->
</div><!-- #primary -->

<?php
get_footer(); // Includes the standard footer

To use a custom content part in page-full-width.php:

  1. Create a file named content-full-width-page.php inside a template-parts folder in your theme.
  2. Modify the page-full-width.php to call get_template_part( 'template-parts/content', 'full-width-page' ); instead of get_template_part( 'template-parts/content', 'page' );.

Code Example (for template-parts/content-full-width-page.php):

<!-- template-parts/content-full-width-page.php -->
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
    </header><!-- .entry-header -->

    <div class="entry-content">
        <?php
        the_content();

        wp_link_pages( array(
            'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'yourtheme' ),
            'after'  => '</div>',
        ) );
        ?>
    </div><!-- .entry-content -->

    <?php if ( get_edit_post_link() ) : ?>
        <footer class="entry-footer">
            <?php
            edit_post_link(
                sprintf(
                    wp_kses(
                        /* translators: %s: Name of current post. Only visible to screen readers */
                        __( 'Edit <span class="screen-reader-text">%s</span>', 'yourtheme' ),
                        array(
                            'span' => array(
                                'class' => array(),
                            ),
                        )
                    ),
                    wp_kses_post( get_the_title() )
                ),
                '<span class="edit-link">',
                '</span>'
            );
            ?>
        </footer><!-- .entry-footer -->
    <?php endif; ?>
</article><!-- #post-<?php the_ID(); ?> -->

Pros: Clean separation of concerns, easy to manage different layouts. Cons: Requires creating a new file for each unique page template.

Method 3: Using get_template_part() with a Dynamic Name

The get_template_part() function allows you to specify a “slug” and an optional “name”. WordPress will then look for files in the order slug-name.php, then slug.php. You can leverage this name parameter dynamically.

Example Scenario: You want different sidebar content based on the page template being used.

Steps:

  1. Create different sidebar files: E.g., sidebar-contact.php, sidebar-about.php.
  2. Modify your page template: In page.php or a custom page template, dynamically set the name parameter for get_template_part().

Code Example (in page.php or a custom page template):

<?php
get_header();
?>

<div id="primary" class="content-area">
    <main id="main" class="site-main">

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

            get_template_part( 'template-parts/content', 'page' );

            // Dynamically load a sidebar based on the page slug or template
            $sidebar_name = '';
            if ( is_page( 'contact' ) ) { // If it's the contact page
                $sidebar_name = 'contact';
            } elseif ( is_page( 'about-us' ) ) { // If it's the about us page
                $sidebar_name = 'about';
            }
            // Add more conditions as needed for other pages/templates

            // If a specific sidebar name is set, load it. Otherwise, load the default.
            if ( $sidebar_name ) {
                get_template_part( 'template-parts/sidebar', $sidebar_name );
            } else {
                get_template_part( 'template-parts/sidebar' ); // Loads sidebar.php or sidebar-default.php
            }

            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;

        endwhile; // End of the loop.
        ?>

    </main><!-- #main -->
</div><!-- #primary -->

<?php
get_footer();
?>

Pros: Flexible, allows for many variations of a single template part. Cons: Requires careful naming conventions for your template part files.

Method 4: Using template_include Filter (Advanced)

This method is more advanced and involves hooking into the template_include filter to programmatically change which template file is loaded for a specific page. This is useful when you need to completely swap out a template file based on complex logic.

Example Scenario: You want a completely different template file for a specific page, overriding the default WordPress template hierarchy.

Steps:

  1. Add code to your functions.php file.
  2. Define your custom template file.

Code Example (in functions.php):

<?php
/**
 * Custom function to filter template loading.
 *
 * @param string $template The path to the template file.
 * @return string The path to the modified template file.
 */
function my_custom_template_for_page( $template ) {
    // Check if it's the page with slug 'special-page'
    if ( is_page( 'special-page' ) ) {
        // Define the path to your custom template file
        $new_template = locate_template( 'page-special.php' ); // Looks for page-special.php in theme root

        // If the custom template exists, use it
        if ( $new_template ) {
            return $new_template;
        }
    }
    return $template; // Return the original template if no match
}
add_filter( 'template_include', 'my_custom_template_for_page' );

Then, create a file named page-special.php in your theme’s root directory and define its content, including any specific template parts you need.

Pros: Powerful for complete template overrides. Cons: More complex, can be harder to debug if not handled carefully.

Best Practices

  • Use Child Themes: Always make these modifications in a child theme. This ensures your changes aren’t lost when the parent theme updates.
  • Organize Template Parts: Store your custom template parts in a dedicated subfolder (e.g., template-parts/) within your theme for better organization.
  • Clear Naming Conventions: Use descriptive names for your custom template files and template parts (e.g., page-contact.php, sidebar-blog.php).
  • Comment Your Code: Explain your conditional logic and custom inclusions for future reference.
  • Test Thoroughly: After making changes, thoroughly test all affected pages to ensure everything works as expected.

By using these methods, you can effectively customize template parts for specific page templates or individual pages in your WordPress site, giving you fine-grained control over your site’s design and content.

Related Posts


WordPress Redirect Issues Across Multiple Websites

Experiencing redirect loops or unwanted redirects on multiple WordPress sites? Here’s a guide to d...

How to detect YouTube iframe tag in a specific WordPress post

Detecting YouTube Iframes in WordPress Posts This document outlines two primary methods for detectin...

“Maximum Available Quantity Has Been Added to Cart” Error in WooCommerce

Seeing the “Maximum available quantity has been added to cart” error in WooCommerce? Thi...

WordPress CSS Issue Caused by User Agent Stylesheet

If your WordPress site’s CSS is being overridden by the user agent stylesheet, it can cause layout...

Recent Posts