The get_sidebar WordPress PHP action fires before the sidebar template file is loaded.
Usage
add_action('get_sidebar', 'your_custom_function', 10, 2); function your_custom_function($name, $args) { // your custom code here }
Parameters
$name
(string|null) – Name of the specific sidebar file to use. Null for the default sidebar.$args
(array) – Additional arguments passed to the sidebar template.
More information
See WordPress Developer Resources: get_sidebar
Examples
Change Sidebar Name Based on Post Type
Change the sidebar name based on the current post type:
add_action('get_sidebar', 'change_sidebar_name_based_on_post_type', 10, 1); function change_sidebar_name_based_on_post_type($name) { if (is_singular('post')) { $name = 'single-post'; } elseif (is_singular('page')) { $name = 'single-page'; } return $name; }
Load Custom Sidebar for a Specific Page
Load a custom sidebar for a specific page by its ID:
add_action('get_sidebar', 'load_custom_sidebar_for_specific_page', 10, 1); function load_custom_sidebar_for_specific_page($name) { if (is_page(42)) { $name = 'custom-sidebar'; } return $name; }
Add Custom Content Before Sidebar
Add custom content before the sidebar is loaded:
add_action('get_sidebar', 'add_custom_content_before_sidebar', 10, 1); function add_custom_content_before_sidebar($name) { if ($name === 'default') { echo '<div class="custom-content">Custom Content</div>'; } }
Add Custom Styles to Sidebar
Add custom styles to the sidebar:
add_action('get_sidebar', 'add_custom_styles_to_sidebar', 10, 1); function add_custom_styles_to_sidebar($name) { if ($name === 'default') { echo '<style>.sidebar { background-color: #f5f5f5; }</style>'; } }
Display Different Sidebar for Logged-in Users
Display a different sidebar for logged-in users:
add_action('get_sidebar', 'display_different_sidebar_for_logged_in_users', 10, 1); function display_different_sidebar_for_logged_in_users($name) { if (is_user_logged_in()) { $name = 'logged-in-sidebar'; } return $name; }