WordPress builds it’s sidebars by default with lists, simple unordered lists. This is very easy for displaying little blocks of information and a couple of widgets. But the markup and styling of a list can be a little more effort. When you are building your own theme, or customizing a existing theme, here are some practical tips and tricks.
As I mentioned before, WordPress builds it’s sidebars with lists. The <ul> and <ol> element have some default styling, that’s different in most browsers, mostly regarding padding and margin. That’s why it can be very easy to use other elements for markup, or use the best of both sides and combine a list with a div.
We will be using the WordPress function register_sidebar(). By default, using this function looks like this (as displayed in the default themes functions.php);
<?php $args = array(
'name' => sprintf(__('Sidebar %d'), $i ),
'id' => 'sidebar-$i',
'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\">',
'after_widget' => '</li>',
'before_title' => '<h2 class=\"widgettitle\">',
'after_title' => '</h2>' );
register_sidebar( $args );
?>
As you can see, this is the place where the markup of each widget is defined. The before_widget and after_widget argument for this function will make each widget contained by a <li> element. That’s what we’re going to change!
If we want to contain each widget in a <div> element for example, that also has a class (widget_class in this example), it will look something like this;
<?php $args = array(
'name' => sprintf(__('Sidebar %d'), $i ),
'id' => 'sidebar-$i',
'before_widget' => '<div class=\"widget_class\">',
'after_widget' => '</div>',
'before_title' => '<h2 class=\"widgettitle\">',
'after_title' => '</h2>' );
register_sidebar( $args );
?>
Off course, this is for you to decide. You could use virtually any element to contain the widgets for your sidebars.
Combining the best of both sides
If you give value to the semantic side of using a list in your sidebar, but really want another element inside that list, you can use the best of both sides. You can simply add a <div> element inside the <li> element. Let’s take a closer look to what I mean;
<?php $args = array(
'name' => sprintf(__('Sidebar %d'), $i ),
'id' => 'sidebar-$i',
'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\"><div class=\"widget_class\">',
'after_widget' => '</div></li>',
'before_title' => '<h2 class=\"widgettitle\">',
'after_title' => '</h2>' );
register_sidebar( $args );
?>
Again, it’s up to you what you create with this powerful, default WordPress function.
A sidenote
WordPress does have something semantic included in it’s sidebar markup. That’s why each widget gets it’s own id that indicated a unique number for each widget.
Personally, I don’t give that much value to that part of WordPress. As long as you keep writing pretty, semantic code, you shouldn’t worry that much about these details. You can always add a id to the <div> elements, or use the combined method.
Related posts: