Replace template part in Custom Page Template for Global Use

In base template (base.php), get_template_part('templates/header') is used for adding the standard header.

For a Custom Page Template for Global Use, a different header should be used.
It should be selectable by user for an arbritary page, so the easy mechanism of using slugs for page-specific template parts doesn’t apply.

Just calling get_template_part('templates/header', 'different'); from within the custom page template script results in duplicate header markup below the actual place where the header goes in the base template.

<?php
/**
 * Template Name: Test
 */
?>
<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('templates/header', 'different'); ?>
<?php endwhile; ?>

So is it possible just treating the header place in base template as placeholder and swapping it out with a different header file from within the Custom Page Template for Global Use?

Alternatively, the header could be omitted from the base template, but then it cannot be used as template standalone, as a Custom Page Template for Global Use is required for adding the default header.

*Or can the base template find out what the Custom Page Template for Global Use looks up so a conditional can be used?

You can put the following in extras.php if you want:

function get_template_header_slug($post_id = null) {
  return basename(\get_page_template_slug($post_id), '.php');
}

Then in your base, you’d do something like…

use Roots\Sage\Extras;

// Then later on ....

  <?php get_template_part('templates/header', Extras\get_template_header_slug()); ?>
// Looks for
// - templates/header-customer-template.php
// - templates/header.php

I haven’t tested that, but it should work or at least give you an idea of where to start. The short answer is: the base template can look up the page template that’s currently in use.

2 Likes