swap sidebar through a hook
-
Is there proper way to swap sidebar through a hook when Content Aware Sidebars is used?
-
Can you explain your use case in more detail? Do you mean that you have a sidebar that is being displayed through a hook, and you want to replace it? Or that you want to add a content aware sidebar to a hook with custom code?
I’d like to swap sidebar with particular conditions that Content Aware Sidebars doesn’t handle.
Is there a hook to swap sidebar for Content Aware Sidebars?
Or Should I just do that with native WP hook?Content Aware Sidebars should be able to replace or merge with any widget area that is registered in WordPress.
https://developer.ww.wp.xz.cn/reference/functions/register_sidebar/It shouldn’t matter how they’re called/displayed, but if you want granular control over the content aware sidebars being fetched, you can use:
WPCACore::get_posts('sidebar');Widgets are generally stored in the global variable
$_wp_sidebars_widgets, so you can do something like this:global $_wp_sidebars_widgets; $sidebars = WPCACore::get_posts('sidebar'); $prefix = 'ca-sidebar-'; foreach($sidebars as $sidebar) { if(isset($_wp_sidebars_widgets[$prefix.$sidebar->ID])) { swap widgets... } }I highly recommend that you use the
dynamic_sidebarfunction instead though, and then let Content Aware Sidebars replace it automatically.Thank you.
Yes my theme is using dynamic_sidebar.
I’ll take a look at WPCACore::get_posts(‘sidebar’); and $_wp_sidebars_widgetswhat I’ve found native wp hook can do I want is dynamic_sidebar_params()
This swaps sidebar depend on cookie.
function my_sidebar_params($params){ if(!is_admin() &&preg_match("/footer-([0-9])/",$params[0]['id'],$rgx) && !empty($_COOKIE['translator-translator-jquery-to'])){ $sdid='footer-'.$rgx[1].'-2'; global $wp_registered_sidebars,$wp_registered_widgets; $sidebar = $wp_registered_sidebars[$sdid]; $sidebars_widgets = wp_get_sidebars_widgets(); foreach((array)$sidebars_widgets[$sdid] as $id){ if(!isset($wp_registered_widgets[$id])) continue; $params = array_merge( array( array_merge( $sidebar, array('widget_id' => $id, 'widget_name' => $wp_registered_widgets[$id]['name']) ) ), (array) $wp_registered_widgets[$id]['params'] ); $classname_ = ''; foreach((array) $wp_registered_widgets[$id]['classname'] as $cn){ if(is_string($cn)) $classname_ .= '_' . $cn; elseif (is_object($cn)) $classname_ .= '_' . get_class($cn); } $classname_ = ltrim($classname_, '_'); $params[0]['before_widget'] = sprintf($params[0]['before_widget'], $id, $classname_); } } return $params; } add_filter('dynamic_sidebar_params','my_sidebar_params');
The topic ‘swap sidebar through a hook’ is closed to new replies.