The dynamic_sidebar() WordPress PHP function displays a dynamic sidebar. The default behavior is to show the ‘sidebar-1’ unless an ID, name, or numerical index is specified for the sidebar.
Usage
Here’s a common way to use the function:
if (is_active_sidebar('left-sidebar')) { echo '<ul id="sidebar">'; dynamic_sidebar('left-sidebar'); echo '</ul>'; }
Parameters
- $index (int|string, Optional): This parameter is used to specify the index, name, or ID of the dynamic sidebar. The default value is 1.
More information
See WordPress Developer Resources: dynamic_sidebar()
This function is often used as a callback when there’s no sidebar.php file to query, or when using sidebars that might not have a template. It’s also useful for rendering dynamic sidebars that may have been generated in the theme’s register_sidebar(array($arguments)) function.
Examples
Display Right Sidebar
Here’s how you can display a right sidebar:
echo '<ul id="sidebar">'; dynamic_sidebar('right-sidebar'); echo '</ul>';
Display Default Sidebar with Fallback
Display the default sidebar with a static fallback when no sidebar is active:
echo '<ul id="sidebar">'; if (!dynamic_sidebar()) { echo '<li>{static sidebar item 1}</li>'; echo '<li>{static sidebar item 2}</li>'; } echo '</ul>';
Using Conditional Statements
Use PHP conditional statements to safely render a dynamic sidebar and provide context if the admin hasn’t assigned a sidebar to a widget:
echo '<section id="sidebar">'; if (is_active_sidebar('sidebar')) { dynamic_sidebar('sidebar'); } else { echo '<div class="meta-default">'; the_widget('WP_Widget_Categories', '', ''); get_search_form(); echo '<nav class="sidebar-login">'; echo '<ul>'; wp_loginout(); echo '</ul></nav></div>'; } echo '</section>';
Displaying a Sidebar with a Specified Numerical Index
To display a sidebar with a specified numerical index, you can do:
dynamic_sidebar(2); // Displays the second registered sidebar
Checking if a Sidebar is Active Before Displaying
Before displaying a sidebar, it’s a good practice to check if it’s active:
if (is_active_sidebar('my_sidebar')) { dynamic_sidebar('my_sidebar'); }
This helps to prevent empty div sections on the page which might create empty space or broken alignment of page view.