Using WordPress ‘get_sidebar()’ PHP function

The get_sidebar() WordPress PHP function loads a sidebar template for a theme. If a specific name is provided, a specialized sidebar will be included.

Usage

get_sidebar( 'sidebar-name', $args );

Parameters

  • $name (string) (Optional) – The name of the specialized sidebar. Default: null
  • $args (array) (Optional) – Additional arguments passed to the sidebar template. Default: array()

More information

See WordPress Developer Resources: get_sidebar()

Examples

Simple call

Load a specialized sidebar named “nice-bar” from a file named “sidebar-nice-bar.php”:

get_sidebar('nice-bar');

Left and Right Sidebars

Include left and right sidebars in a theme:

get_header();
get_sidebar('left');
get_sidebar('right');
get_footer();

File names should be “sidebar-left.php” and “sidebar-right.php”.

Multi sidebars

Load different sidebars for different pages:

if (is_home()) {
    get_sidebar('home');
} elseif (is_404()) {
    get_sidebar('404');
} else {
    get_sidebar();
}

File names should be “sidebar-home.php” and “sidebar-404.php”.

Simple 404 page

Create a simple 404 error page template:

get_header();
echo '<h2>Error 404 - Not Found</h2>';
get_sidebar();
get_footer();

Call sidebar with $args parameter (Since 5.5.0)

Call a sidebar with additional arguments:

$args = array('title' => 'Shop sidebar');
get_sidebar('shop', $args);

Inside “sidebar-shop.php”, use the passed arguments:

echo '<div id="secondary" class="widget-area sidebar-shop" role="complementary">';
echo '<h2>' . esc_html($args['title']) . '</h2>';
dynamic_sidebar('sidebar-shop');
echo '</div>';

Conditional Statement for Any Sidebar

Check if any sidebar exists before calling it:

if (function_exists('register_sidebar')) {
    get_sidebar();
}

Or, check for a specific registered sidebar:

if (is_active_sidebar('content-bottom')) {
    get_sidebar('content-bottom');
}