¿Estás buscando una forma de crear y adjuntar barras laterales dinámicamente a páginas o entradas? Si bien es probable que haya un plugin para esto, hemos creado un fragmento de código rápido que se puede utilizar para crear dinámicamente y adjuntar barras laterales a las páginas o mensajes.
Este fragmento le permitirá crear fácilmente nuevas barras laterales simplemente añadiendo el nombre a una matriz. También podrá definir la barra lateral creada dinámicamente que cargará una página seleccionándola en el metabox de selección de barras laterales personalizadas.
En primer lugar, se creará un nuevo metabox en el editor de páginas que le permitirá adjuntar una de las barras laterales creadas dinámicamente. En segundo lugar, observará una serie de nombres, por ejemplo: Sidebar 01, Sidebar 02, etc. Estos son los nombres de las barras laterales creadas dinámicamente que puede cambiar o añadir nuevas barras laterales.
Instrucciones:
Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio
$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> '; }
Copie el siguiente fragmento de código y reemplace todo el código dentro de la plantilla sidebar.php de su tema de WordPress y estará todo listo.
<!-- 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 -->
Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo copiar / pegar correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.
Si te ha gustado este fragmento de código, por favor, considere revisar nuestros otros artículos en el sitio como: 10 mejores plugins de WordPress para desarrolladores web y cómo crear un formulario multipágina en WordPress.
change your code.
<?php
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 !!!
hi Kevin
The dropdownbox is not working in wordpress3.8. any ideas
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!
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(); ?>
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
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?
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.
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.
I’m looking at turning this into a plugin so that people can have an admin interface to create new sidebars.
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?
Question…
Does there need to be some level of sanitizing for this to be added to a theme for security?
Hi, thanks for this snippet. How can add the selection to categories?
If I understand correctly do you mean assign sidebars based on the category?
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
No problem glad to hear you like the snippet.
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?
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 ?
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!
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.
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
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.
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 ”; } ?>
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! 🙂
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.
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?
Hi Hakan, you see the code within the page?
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.
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 🙂 ).
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.
Good point. Let me know when you have it done (or if you do it in the end) 🙂