get_sidebar()
Connects the template file sidebar.php (sidebar). If the parameter $name is passed, the file sidebar-{name}.php will be included.
If the file is not found in the theme template, the default file will be taken: wp-includes/theme-compat/sidebar.php
Hooks from the function
Returns
null|false. null on successful file inclusion, false if the template file does not exist.
Usage
<?php get_sidebar( $name, $args ); ?>
- $name(string)
- The index of the file name. The file
sidebar-{name}.phpwill be included.
Default: null - $args(array) (Since WP 5.5)
- Additional parameters for the included file.
In the included file, the variable$argsshould then be used.
Default: array()
Examples
#1 Simple call
Assume you have file wp-content/themes/yourTheme/sidebar-nice.php. The way you can include this sidebar in your page is:
<?php get_sidebar('nice'); ?> #2 Two sidebars in one theme
<?php get_header(); ?>
<?php get_sidebar('left'); ?>
<?php get_sidebar('right'); ?>
<?php get_footer(); ?>
The theme (template) must contain files sidebar-right.php and sidebar-left.php.
#3 Connecting a sidebar from a theme subfolder
To do this, you need to write your own simple analog of this function:
// Plug in the 'inc/sidebar.php' file from the current theme folder.
// Place in functions.php
function theme_sidebar( $name = '' ){
do_action( 'get_sidebar', $name );
if( $name ) {
$name = "-$name";
}
locate_template( "inc/sidebar$name.php", true );
}
// call instead of get_sidebar()
theme_sidebar(); #4 Multi sidebars
Different sidebar for different pages.
<?php if ( is_home() ) : get_sidebar( 'home' ); elseif ( is_404() ) : get_sidebar( '404' ); else : get_sidebar(); endif; ?>
The file names for the home and 404 sidebars should be sidebar-home.php and sidebar-404.php respectively.
#5 Conditional Statement
Include sidebar file only if there is any widgets added in it:
// check if there is any widgets in sidebar area
if ( is_active_sidebar( 'content-bottom' ) ) {
get_sidebar( 'content-bottom' );
}
See also: is_active_sidebar().
#6 Call sidebar with $args parameter (Since 5.5.0)
Consider below is your sidebar call from anywhere inside your theme:
<?php $args = array( 'title' => 'Shop sidebar' ); get_sidebar( 'shop', $args ); ?>
Your codes inside sidebar-shop.php file might look a like below.
<div class="widget-area sidebar-shop"> <h2><?php echo esc_html( $args['title'] ); ?><h2> <?php dynamic_sidebar( 'sidebar-shop' ); ?> </div>
Changelog
| Since 1.5.0 | Introduced. |
| Since 5.5.0 | A return value was added. |
| Since 5.5.0 | The $args parameter was added. |