X

Comment créer et attacher dynamiquement des barres latérales à des pages ou à des articles ?

Snippets by IsItWP

Vous cherchez un moyen de créer et d’attacher dynamiquement des barres latérales à des pages ou à des articles ? Bien qu’il existe probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour créer et attacher dynamiquement des barres latérales aux pages ou aux articles.

Ce snippet vous permettra de créer facilement de nouvelles barres latérales en ajoutant simplement le nom à un tableau. Vous pourrez également définir la barre latérale créée dynamiquement et chargée par une page en la sélectionnant dans la métabox de sélection de la barre latérale personnalisée.

Tout d’abord, une nouvelle métabox sera créée dans l’éditeur de pages, vous permettant d’attacher l’une des barres latérales créées dynamiquement. Deuxièmement, vous remarquerez un tableau de noms, par exemple : Sidebar 01, Sidebar 02, etc. Ce sont les noms des barres latérales créées dynamiquement que vous pouvez modifier ou auxquelles vous pouvez ajouter de nouvelles barres latérales.

Instructions:

Tout ce que vous avez à faire est d’ajouter ce code dans le fichier functions.php de votre thème ou dans un plugin spécifique à votre site.

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

Copiez l’extrait de code ci-dessous et remplacez tout le code dans le modèle sidebar.php de votre thème WordPress et vous êtes prêt.

<!-- 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 : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez vous référer à notre guide sur la façon de copier/coller correctement des extraits de code dans WordPress, afin de ne pas briser accidentellement votre site.

Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 10 meilleurs plugins WordPress pour les développeurs web et comment créer un formulaire multi-pages dans WordPress.

Commentaires   laisser une réponse

  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 mai 11, 2013 à 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 novembre 4, 2011 à 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 novembre 4, 2011 à 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) 🙂

Ajouter un commentaire

Nous sommes heureux que vous ayez choisi de laisser un commentaire. N'oubliez pas que tous les commentaires sont modérés conformément à notre privacy policy, et que tous les liens sont en nofollow. N'utilisez PAS de mots-clés dans le champ du nom. Engageons une conversation personnelle et constructive.

WordPress Launch Checklist

L'ultime liste de contrôle pour le lancement de WordPress

Nous avons rassemblé tous les éléments essentiels de la liste de contrôle pour le lancement de votre prochain site Web WordPress dans un ebook pratique.
Oui, envoyez-moi le gratuit !