Lab | September 1st, 2014

How to Use Custom Sidebars on Posts and Pages

Today I’d like to show you how to easily add custom sidebars to use within your posts and pages. It could be useful to display different widgets according to your page or post’s topic.

Step 1 Adding Meta Boxes

First, we’ll simply add our meta boxes. We need to declare two meta boxes, one for posts and one for pages. We also need to register two hooks, one to add meta boxes and the other one to save them.

Open your functions.php file and add this:

/* Define the custom box */

add_action( 'add_meta_boxes', 'add_sidebar_metabox' );
add_action( 'save_post', 'save_sidebar_postdata' );

/* Adds a box to the side column on the Post and Page edit screens */
function add_sidebar_metabox()
{
    add_meta_box( 
        'custom_sidebar',
        __( 'Sidebar Position', 'custom' ),
        'custom_sidebar_callback',
        'post', /* displays on posts */
        'side'
    );
    add_meta_box( 
        'custom_sidebar',
        __( 'Sidebar Position', 'custom' ),
        'custom_sidebar_callback',
        'page', /* displays on pages */
        'side'
    );
}

Create the Callback Function

Now, let’s create the custom_sidebar_callback function, which will print out the meta boxes’ markup.

There’re several key steps in this function:

/* Prints the box content */
function custom_sidebar_callback( $post )
{
    global $wp_registered_sidebars;

    $custom = get_post_custom($post->ID);

    if(isset($custom['custom_sidebar']))
        $val = $custom['custom_sidebar'][0];
    else
        $val = "default";

    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), 'custom_sidebar_nonce' );

    // The actual fields for data entry
    $output = '<strong>Select Sidebar</strong><p><label for="sidebar">'.__("", 'fe' ).'</label></p>';
    $output .= "<select name='custom_sidebar'>";

    // Add a default option
    $output .= "<option";
    if($val == "default")
        $output .= " selected='selected'";
    $output .= " value='default'>".__('None', $themename)."</option>";

    // Fill the select element with all registered sidebars
    foreach($wp_registered_sidebars as $sidebar_id => $sidebar)
    {
        $output .= "<option";
        if($sidebar_id == $val)
            $output .= " selected='selected'";
        $output .= " value='".$sidebar_id."'>".$sidebar['name']."</option>";
    }

    $output .= "</select>";

    echo $output;
}

Save Meta Box

Now let’s save our post meta. Again several steps here:

/* When the post is saved, saves our custom data */
function save_sidebar_postdata( $post_id )
{
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
      return;

    // verify this came from our screen and with proper authorization,
    // because save_post can be triggered at other times

    if ( !wp_verify_nonce( $_POST['custom_sidebar_nonce'], plugin_basename( __FILE__ ) ) )
      return;

    if ( !current_user_can( 'edit_page', $post_id ) )
        return;

    $data = $_POST['custom_sidebar'];

    update_post_meta($post_id, "custom_sidebar", $data);
}

Step 2 Displaying the selected sidebar

Now everything is correctly set up, what’s left to do is updating our templating files so that they can display custom sidebars.

To display the correct sidebar you will need to edit the sidebar.php or any file that is handling your sidebar files. For this demonstration I will be using sidebar.php.

In sidebar.php add the below code.

<aside id="sidebar">
<?
     global $post;
          $custom  = get_post_custom($post->ID);
	  $link    = $custom["custom_sidebar"][0];
     if($link != ''){
           echo '<ul id="widgets">';
     if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar($link) ) :
           endif;
           echo '</ul>';
}
?>
</aside>

To switch between a custom sidebar and the default one, change the get_sidebar() call at the bottom of this same file to this:

<?php $sidebar = get_post_meta($post->ID, "sidebar", true); get_sidebar($sidebar);?>

Now your page should display the sidebar you chose.

Conclusion

That’s all folks! Now you can use unlimited sidebars for your pages and posts. This is just one solution among others, but it’s a quick and easy way to implement custom sidebars, so don’t hesitate to leave a comment, share your ideas, and give feedback!