I’m writing a custom plugin that allows a particular page to have it’s own sidebar with widgets. It works great so far, but what I’d like to do is generalize it more and allow the plugin to “override” the dynamic sidebar of any page (if it has a custom sidebar) without having to edit any template files.
I’ve tried several hooks and have delved into the code a bit, but nothing stands our or works so far.
To save some time I thought I’d see if anybody has any working solutions to this issue? I might be able to solve this issue, but it is straining my “after working hours” brain.
If it isn’t possible I’d be more than willing to have a short-code or function call that does this for me, but I’d really like to make it idiot proof and just have it work without any template changes.
dynamic_sidebar()
callswp_get_sidebars_widgets()
to get the list of all sidebars and their widgets. This output is filtered throughsidebars_widgets
, so you can modify it to add or remove widgets.This array only contains widget IDs, so you need to register the widget instance too (it should end up in the global
$wp_registered_widgets
array). I think you can do this withwp_register_sidebar_widget()
, but it is possible that this is older code from the time when a widget could not have multiple instances yet.Yes, its totally possible, but not the easiest thing that can be done. It took me about two months to perfect it when I was working on Total Widget Control, but I was able to do it.
It’s not a direct override tho, what happens is that
dynamic_sidebar
loads the$registered_widgets
global and loops through the widgets, triggering the callback for each of these widgets.So what I ended up doing was grabbing this
registered_widgets
global, backing it up to my own global and then replacing the original callbacks with an empty callback function.This way
dynamic_sidebars
was still called, but it doesn’t actually do anything.The next step was a bit trickier and took a bit of debugging. I had to take a total count of the original widgets for the given sidebar, and then keep track of what loop that
dynamic_sidebars
was on. Whendynamic_sidbars
reached its last widget, I called my owndo_action('trigger_new_sidebar')
.This basically allows me to start adding actions to this trigger and displaying any widgets that I wanted to display.