X

How to Dynamically Create and Attach Sidebars to Pages or Posts

Snippets by IsItWP

Are you looking for a way to dynamically create and attach sidebars to pages or posts? While there’s probably a plugin for this, we have created a quick code snippet that you can use to dynamically create and attach sidebars to pages or posts.

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.

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.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin

    $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>
	';
}

Copy the below snippet of code and replace all the code within your sidebar.php template of your WordPress theme and you’re all set.

<!-- 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 -->

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 10 best WordPress plugins for web developers and how to create a multi-page form in WordPress.

Comments   Leave a Reply

  1. change your code.

    <?php

  2. Hi Kevin,

    Thanks for code. I need a help. I want to display 2nd sidebar below the 1st one. how can i do this?? Please help me !!!

  3. hi Kevin

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

  4. Crvenkoski Mihajlo May 11, 2013 at 9:41 am

    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!

  5. 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(); ?>

  6. 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

  7. 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?

  8. 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.

  9. 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.

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

    2. 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?

  10. Question…

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

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

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

  12. 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

    1. No problem glad to hear you like the snippet.

  13. 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?

    1. 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 ?

      1. 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!

        1. 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.

  14. 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

    1. 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.

  15. 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 ”; } ?>

  16. Antonin Januska November 4, 2011 at 4:39 pm

    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! 🙂

    1. 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.

  17. 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?

    1. Hi Hakan, you see the code within the page?

    2. 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.

      1. Antonin Januska November 4, 2011 at 4:42 pm

        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 🙂 ). 

        1. 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.

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

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!