I have this code in a template file, which loads sidebar-sidebar_a.php
:
get_sidebar('sidebar_a');
I would like to add a function to sidebar.php which has the effect of changing that to this if some condition is met:
get_sidebar('other');
so that it instead loads sidebar-other.php
.
I thought that this would work, but it seems to have no effect:
add_action('get_sidebar', 'my_sidebar_logic');
function my_sidebar_logic($sidebar) {
// Load a different sidebar if the user is logged in
if (is_user_logged_in()) {
return 'other';
}
return $sidebar;
}
What can I do to get the effect I want?
Get sidebar is a really thin wrapper around
locate_template
, which just searches the current child theme and parent theme directory for the given sidebar.get_sidebar
inwp-includes/general-template.php
:}
And
locate_template
(inwp-includes/template.php
):The reason your hook into
get_sidebar
doesn’t work is because it’s an action. It just fires. It doesn’t allow you to change the result. Your sidebar will still be included regardless of the your hooked action.That levels you a few options.
1. Pass a variable into
get_sidebar
Chip Bennett’s solution: pass a variable into the
get_sidebar
function. Not bad.2. Write Your Own Sidebar Logic
And use it in place of
get_sidebar
. A simple example:Then use your own filter to modify the sidebar
This will be the most flexible. If it’s a public theme, end users will be able to customize things. If it’s for a client, when the inevitably ask you for more stuff, it’s easily done.
3. Look Deeper
get_sidebar
just includes the appropriate theme files.dynamic_sidebar
is where the work is done.If you take a look inside that function, the most interesting line is:
wp_get_sidebars_widgets
fetches all the currently registered widgets for all sidebars on the site.The key line there:
apply_filters('sidebars_widget', ...)
. Money.Register a secondary sidebar only for logged in users:
Then hook into
sidebars_widgets
and swap the normal sidebar for the logged in version.Just pass a variable to
get_sidebar()
:Themes
Just wrap it in the thinnest and most unintrusive logic: A filter.
Then you can switch in your functions.php file:
Plugins
If you want to do it from a plugin, use the action:
You can call the actual sidebar in the function as well.