Widgetizing a Sidebar in WordPress

written by: jason
Widgetizing a Sidebar in WordPress

How do you “widgetize” your WordPress sidebar? It’s actually pretty easy. But first, what is a widget? A widget is a little piece of code that creates a module that you can drag anywhere into your sidebar via the admin area of your WordPress install. A couple of examples might be a calendar or tag cloud. You can find the widget area under “Appearance” in the left hand column.
If you are using lists as your sidebar.php, i.e. category lists, page lists, blogroll etc, then you would have something that looks like this in your html.

  1. <ul id="sidebar">
  2.    <li id="categories">
  3.       <h2>HTML</h2>
  4.         <p>link goes here</p>
  5.    </li>
  6.    <li id="links">
  7.       <h2>Blogroll</h2>
  8.         <p>link goes here</p>
  9.         <p>link goes here</p>
  10.         <p>link goes here</p>
  11.    </li>
  12. </ul>
<ul id="sidebar">
   <li id="categories">
      <h2>HTML</h2>
        <p>link goes here</p>
   </li>
   <li id="links">
      <h2>Blogroll</h2>
        <p>link goes here</p>
        <p>link goes here</p>
        <p>link goes here</p>
   </li>
</ul>

It consists of two list items (categories and links) with titles (HTML and Blogroll) wrapped in h2 tags. Now, all we have to do is add three lines of code inside our unordered list and we’re all set (lines 2, 3 and 14 below).

  1. <ul id="sidebar">
  2. <?php if ( !function_exists('dynamic_sidebar')
  3.        || !dynamic_sidebar() ) : ?>
  4.    <li id="categories">
  5.       <h2>HTML</h2>
  6.         <p>link goes here</p>
  7.    </li>
  8.    <li id="links">
  9.       <h2>Blogroll</h2>
  10.         <p>link goes here</p>
  11.         <p>link goes here</p>
  12.         <p>link goes here</p>
  13.    </li>
  14. <?php endif; ?>
  15. </ul>
<ul id="sidebar">
<?php if ( !function_exists('dynamic_sidebar')
        || !dynamic_sidebar() ) : ?>
   <li id="categories">
      <h2>HTML</h2>
        <p>link goes here</p>
   </li>
   <li id="links">
      <h2>Blogroll</h2>
        <p>link goes here</p>
        <p>link goes here</p>
        <p>link goes here</p>
   </li>
<?php endif; ?>
</ul>

Cool! That was simple. But not so fast. We aren’t quite finished yet. Open your functions.php file and make this small addition to it. Once you do that, you can visit the “widgets” section in your WordPress admin area and drag all the widgets that you want into your sidebar. 🙂

  1. <?php
  2. if ( function_exists('register_sidebar') )
  3.     register_sidebar();
  4. ?>
<?php
if ( function_exists('register_sidebar') )
    register_sidebar();
?>
Tags: , ,

Comments are closed.