get_sidebar()
Includes the sidebar.php template file from your current theme's directory. If a $name is specified then sidebar-{name}.php will be included.
If the theme contains no sidebar.php file then the sidebar from the default theme wp-includes/theme-compat/sidebar.php
will be included.
Hooks from the function
Return
null|false
. Void on success, false if the template does not exist.
Usage
get_sidebar( $name, $args );
- $name(string)
- The name of the specialized sidebar.
Default: null - $args(array)
- Additional arguments passed to the sidebar template.
Default: empty 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. |