Dynamically Include Sidebars in WordPress Page Templates for Specific Pages

by | August 12, 2022 | PHP, Website Development

This page may contain affiliate links to recommended products or services. If you choose to purchase after clicking a link, I may receive a commission at no additional cost to you.

Last updated on: February 8, 2023

Obligatory throat clearing… I want to include dynamic sidebars in WordPress page templates.

Context

When creating a “Page” in WordPress you have the option to assign a page template. Page templates allow you to apply a custom layout to a page. That’s to say, as long as the active theme on your website offers page templates you can apply a page template. Some themes rely on block editors for layout and structure and don’t offer page templates, but all themes work with page templates if you create the required PHP files.

It’s possible to create a specific page template for each specific page. However, I like to take a broader more generalized object oriented approach to page templates. Instead of page templates tied to individual pages — like an about-page-template for the About page on your website — I like to create page templates tied to the layout styles of the site.

For example, template-page-sidebar-left.php for pages I want to have a sidebar on the left or template-page-sidebar-right.php for pages I want to have a sidebar on the right.

The idea is to create a reusable page template for any page-style that’s not the default page style that can be repurposed for an infinite number of pages without needing an infinite number of page templates.

That said, I also sometimes want to include specific custom sidebars (or widgets, widget areas, custom content, etc.) in those generalized page templates. And, I don’t necessarily want to use a WordPress plugin to make it happen.

As an example, you could assign a page template featuring a left-hand-sidebar to the “About” page of your website and have specific content for that sidebar that should only display on the About-page and not any other page that’s using the left-hand-sidebar page template.

You could install a plugin to achieve the desired results, but that’s an easy way to convolute the widget-area-dashboard, overwhelm yourself with options and select inputs, and forever need to be on the lookout for plugin updates and vulnerabilities in someone else’s code on your website.

There’s probably a better, easier, and programmatic way to do that.

Goal

Instead of using a plugin to dynamically include specific sidebars inside generalized page templates I’m proposing a simple and programmatic code-based-solution. Without manually assigning a sidebar, creating options, or keeping track of files I want a solution that will automatically determine if a specific sidebar exists and include it instead of the default option if it does. I want my page templates to be smart.

This “smart” dynamic include doesn’t necessarily need to be a sidebar, but in my plan I’m taking advantage of WordPress’ existing get_sidebar() functionality, so that’s what I’m talking about.

Here’s the plan:

  • Automatically determine if a specific sidebar exists for the current page.
  • Include the specific sidebar instead of the default sidebar if one exists.
  • Include the default sidebar if a specific sidebar does not exist.

That’s easy enough, so let’s get to it.

Solution

The get_sidebar() function accepts an optional argument $name. By default, get_sidebar() essentially does what we’re trying to do — it looks for a file named sidebar.php and includes. Passing the $name argument to get-sidebar allows you to modify the functionality to look for and include a file named sidebar-name.php, where name is whatever text-string you provide. That’s our leverage.

So first, let’s programmatically build out a filename. From within a page template’s file, the current page’s information is readily available via a variable called $post. We can use the page’s slug as the dynamic filename appendage by accessing $post->post_name like so:

$sidebar_filename = 'sidebar-' . $post->post_name . '.php'

For the About page, that will produce the filename sidebar-about.php. Perfect!

Next, let’s use that to check if a file matching that filename exists, so we can determine if the current page has a custom sidebar (or not).

$has_custom_sidebar = file_exists(__DIR__ . '/' . $sidebar_filename);

Here, we’re using PHP’s built-in file_exists() function to literally check if a file exists. As the argument to file_exists(), we’re passing in the dynamic filename we created and prepending __DIR__ . '/' to tell it to search in the current directory — theoretically, your page template files are in the same folder as the sidebar files, but feel obliged to adjust the path according to your needs if that isn’t the case.

Lastly, now that we know whether or not a custom sidebar file exists we can include it (or not).

if( $has_custom_sidebar ) {
  get_sidebar($post->post_name);
}
else {
  get_sidebar();
}

All together, here’s what the PHP code looks like. You can add it to your theme’s page-template file(s).

/*
* Include custom sidebar if it exists.
*/
$sidebar_filename = 'sidebar-' . $post->post_name . '.php';
$has_custom_sidebar = file_exists(__DIR__ . '/' . $sidebar_filename);
if( $has_custom_sidebar ) {
  get_sidebar($post->post_name);
}
else {
  get_sidebar();
}

To recap, this code checks the current directory for a specific sidebar file matching the pattern sidebar-<page-slug>.php and includes it in lieu of the default sidebar.php. Voila — dynamically include sidebars and widgets in WordPress pages without using a plugin.

Floyd Hartford is a website developer from southern Maine. He's focused on creating and building WordPress websites and loves spending time digging into code like HTML, CSS, scss, jQuery, PHP, and MySQL.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

seventeen − three =

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Looking for WordPress Help?

I’m a freelance web developer specializing in small business and corporate marketing websites.

Pin It on Pinterest