wordpress snippets last updated   : July 14, 2014
we now have 634 snippets

Dynamically create and attach sidebars to pages or posts

wordpress snippet

This is a bit large for the snippets I normally post however very useful. This snippet will let you easily create new sidebars by simply adding the name to an array. You will also be able to define the dynamically created sidebar a page loads by selecting from the custom sidebar selection metabox.

Adding the first snippet to the functions.php of your wordpress theme will do a few things. First it will create a new metabox within the pages editor letting you attach one of the dynamically created sidebars. Second you will notice an array of names eg: Sidebar 01, Sidebar 02 etc. these are the names of the dynamically created sidebars that you can change or add new sidebars to. Copy the second snippet of code and replace all the code within your sidebar.php template of your wordpress theme and you are all set. ( example screenshot )
snippet :  PHP - functions.phpcopy
    $dynamic_widget_areas = array(
		/* rename or create new dynamic sidebars */
		"Sidebar 01",
		"Sidebar 02",
		"Sidebar 03",
		"Sidebar 04",
		"Sidebar 05",
		"Sidebar 06",
		"Sidebar 07",
		"Search Template",
		);
if ( function_exists('register_sidebar') ) {
    foreach ($dynamic_widget_areas as $widget_area_name) {
        register_sidebar(array(
           'name'=> $widget_area_name,
           'before_widget' => '<div id="%1$s" class="widget %2$s left half">',
           'after_widget' => '</div>',
           'before_title' => '<h3 class="widgettitle">',
           'after_title' => '</h3>',
        ));
    }
}
	add_action("admin_init", "sidebar_init");
	add_action('save_post', 'save_sidebar_link');
	function sidebar_init(){
		add_meta_box("sidebar_meta", "Sidebar Selection", "sidebar_link", "page", "side", "default");
	}
	function sidebar_link(){
		global $post, $dynamic_widget_areas;
		$custom  = get_post_custom($post->ID);
		$link    = $custom["_sidebar"][0];
	?>
<div class="link_header">
	<?
	echo '<select name="link" class="sidebar-selection">';
	echo '<option>Select Sidebar</option>';
	echo '<option>-----------------------</option>';
	foreach ( $dynamic_widget_areas as $list ){
		    if($link == $list){
		      echo '<option value="'.$list.'" selected="true">'.$list.'</option>';
			}else{
		      echo '<option value="'.$list.'">'.$list.'</option>';
			}
		}
	echo '</select><br />';
	?>
</div>
<p>Select sidebar to use on this page.</p>
<?php
}
function save_sidebar_link(){
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {return $post->ID;}
	update_post_meta($post->ID, "_sidebar", $_POST["link"]);
}
add_action('admin_head', 'sidebar_css');
function sidebar_css() {
	echo'
	<style type="text/css">
		.sidebar-selection{width:100%;}
	</style>
	';
}
snippet :  PHP - sidebar.phpcopy
<!-- begin sidebar -->
<div id="sidebar">
<?
	   global $post;
	   $custom  = get_post_custom($post->ID);
	   $link    = $custom["_sidebar"][0];
	if($link != ''){
	    echo '<ul id="widgets">';
		if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar($link) ) :
		endif;
	    echo '</ul>';
	}
?>
</div>
<!-- end sidebar -->

  • Hakan

    Hi Kevin,
    When I apply your code, I see 

    “‘; echo ”; echo ”; foreach ( $dynamic_widget_areas as $list ){ if($link == $list){ echo ”; }else{ echo ”; } } echo ‘
    ‘; ?>
    Select sidebar to use on this page.”

    on my page sidebar at “Sidebar Selection”

    Do you have any idea about that?

    • http://wpsnipp.com Kevin Chard

      Hi Hakan, you see the code within the page?

    • http://wpsnipp.com Kevin Chard

      Hi Hakan,
      I uploaded the first part to function like a plugin so this may be easier for you to setup.
      http://wpsnipp.com/wp-content/uploads/2011/11/sidebars.php_.zip
      Open the zip and upload this file to your plugins folder, then add the second code above to replace your sidebar code. Don’t forget to activate the plugin called attach sidebars. Hope this helps.

      • http://twitter.com/AntJanus Antonin Januska

        Did you publish this for WordPress? If you do, send me a link over twitter (@antjanus), I’ll write an article about it (and recommend it to everyone :) ). 

        • http://wpsnipp.com Kevin Chard

          As a plugin it is limited, I was thinking the reason Hakan had a problem was just the location within the functions.php file so I just made it a plugin to fix his issue faster. It needs to have some sort of interface so people can add new sidebars before I can release it as a plugin as the array is not practical.

          • http://about.me/antoninjanuska Antonin Januska

            Good point. Let me know when you have it done (or if you do it in the end) :)

  • http://twitter.com/AntJanus Antonin Januska

    Great idea. I’ve been having to create separate sidebar template pages, or just separate templates for my website because I tended to use a lot of sidebars (custom sidebars for each page I created basically). I think it’s awesome to use for A/B testing, and advanced marketing (specific CTAs in the sidebar linked to specific pages). Thanks! :)

    • http://wpsnipp.com Kevin Chard

      Hi Antonin
      Glad to hear you like it, I posted a while back about just the first half to create the side bars part using the array. Then when working on a theme I needed to attach them I come up with this idea.

  • Hakan

    Hi Kevin,

    I’m sorry but result is same. No change. On my admin area, I’m getting :

    ‘; echo ”; echo ”; foreach ( $dynamic_widget_areas as $list ){ if($link == $list){ echo ”; }else{ echo ”; } } echo ‘
    ‘; ?>Select sidebar to use on this page.
    under Sidebar Selection part at the right side and on the preview site, I’m getting :

    ID); $link = $custom["_sidebar"][0]; if($link != ”){ echo ”; if ( !function_exists(‘dynamic_sidebar’) || !dynamic_sidebar($link) ) : endif; echo ”; } ?>

  • Hakan

    Hi again,

    I’m sorry, I was working on my localhost, I tried to upload it to my hosting and it worked without any problem. Do you have any idea why it is not working on Wampserver. 

    And where can wordpress admin add new sidebar ? Only from that array or is there any Add New Sidebar option on preview screen? I couldn’t see such a add option.

    Thanks for your great snippets again.

    Hakan

    • http://wpsnipp.com Kevin Chard

      Hi Hakan, Glad to hear you got things working although it is very strange that it will not work locally to be honest I’m not sure why. In regards to updating as of right now you need to still update the array. Although because of the feedback I’m getting I may fix things up and release it as a plugin in the future with an admin interface.

      Thanks again Hakan glad to hear you like the snippets.

  • http://tightmixblog.com Chris B.

    hmm i cant seem to get this to work. i keep getting the following error: “Undefined index: _sidebar in [THEME_PATH]/functions.php on line 97

    the select box shows up on the edit page screen, but none of the sidebars created in the array appear in the drop down menu. any ideas how to remedy this?

    • http://wpsnipp.com Kevin Chard

      Hi Chris,
      Well make sure that your sidebar is empty just use the code I posted above. The _sidebar is where the info is saved. Where is the error displayed? is it on the editor page or when you try and save your functions.php ?

      • http://tightmixblog.com Chris B.

        Kevin,

        Thanks for your response. When I visit the “Edit Page” screen where the meta box is added, the sidebars that I stored in the “$dynamic_widget_areas” array are not displaying in the “Sidebar Selection” drop down box as an option. Instead, I get the following errors in my debug log:

        “Undefined index: _sidebar in [THEME_PATH]/functions.php on line 110″

        “PHP Warning:  Invalid argument supplied for foreach() in [THEME_PATH]/functions.php on line 118″

        Also, when I visit a page that is supposed to display a sidebar, I get this error: 

        “Undefined index: _sidebar in [THEME_PATH]/sidebar.php on line 17″

        I have not altered your code above, and yes, I’m putting them in the correct places. Any help is greatly appreciated!

        • http://wpsnipp.com Kevin Chard

          hhmmm Chris, this is odd you wouldn’t happen to have a plugin that would cause problems with this code? or other code within the functions.php ? if you still have problems Ill set it up as a plugin you can download see if that resolves things.

  • Ajayvats

    I m very happy with this post & very useful specially for me. I hope it’s also useful for other worpress user. Great work by you Dear Kevin Chard. Thanks

    • http://wpsnipp.com Kevin Chard

      No problem glad to hear you like the snippet.

  • http://www.dietmarhartje.de/ Info

    Hi, thanks for this snippet. How can add the selection to categories?

    • http://wpsnipp.com Kevin Chard

      If I understand correctly do you mean assign sidebars based on the category?

  • http://twitter.com/SimonWebDesign Simon Urbina

    Question…

    Does there need to be some level of sanitizing for this to be added to a theme for security?

  • http://www.facebook.com/drbeaven Daniel Beaven

    thanks for this,sved my day lol,one issue is it only appears in post or page and not post and page,i got round it by adding the following to the sidebar_init function:

     add_meta_box("sidebar_meta", "Sidebar Selection", "sidebar_link", "page", "side", "default");

    I would however love it to be a little more dynamic,like instead of pre-defining the amount of sidebars created, allow the admin user to input a qty of sidebars to be created then display those in the drop down.any ideas how? 

    thanks for a great snippet.

    • http://wpsnipp.com Kevin Chard

      I’m looking at turning this into a plugin so that people can have an admin interface to create new sidebars.

    • Anonymous

      Daniel, could you post a larger snippet of this? Implemented the above code in my theme, but I wan’t sure where your addition would need to go… is this part of the sidebar.php file, or in the functions file?

  • Himanshu Jain

    Hello Friends,

    I am using the code in thesis. Everything looks great for me except one thing.
    I have renamed “Sidebar 01″ to “Product 01″ and it is therefore changed under my edit post area but in the widget area its still showing me Sidebar 01 and respectively..Can somebody help me so that the name in the widget area can also be changed??Thanks & Regards.

  • Surb

    Notice: Undefined index: _sidebar in /home/

    I am getting this error in the sidebar in archive.php and pages, posts with no sidebar selected.

    Doesn’t pass debug. Any ideas?

  • j.r.

    everything works great,
    but seems that you don’t know what sidebar is selected when you go back to the your page. did i implement it wrong? or is there an easy way to have the dropdown preselected if  that pages sidebar is choosen…

    thanks

  • http://twitter.com/kelvinalfonso Wake Up Frank

    If anyone has a problem with the sidebar not showing try this out instead of part 2:

    post->ID;
    $link = get_post_meta($postid, ‘_sidebar’, true);
    if($link != ”){
    echo ”;
    if (function_exists(‘dynamic_sidebar’) && dynamic_sidebar(($link))) :endif;
    echo ”;
    } wp_reset_query(); ?>

  • http://www.facebook.com/m.crvenkoski Crvenkoski Mihajlo

    Hi Kevin.
    I am kind of new in this and need little bit help. I install this plugin but i have problems with css, any tips?
    Btw this plugin is awesome!

  • pietergoosen

    hi Kevin

    The dropdownbox is not working in wordpress3.8. any ideas

jqsnipp.com | we just launched jquery snippets website