How to Widgetize your WordPress sidebar
by Bandicoot Marketing on | Posted in Tutorials | 29 comments
WordPress widgets are great. They have tons of amazing functions and are extremely easy to use. The only problem is that not all themes support them. But that is a problem that is very easily solved with just a little bit of coding.
First you need to open up your theme’s functions.php file. IF you don’t have one, create one and place it in your theme’s directory. Make sure you have an opening and closing PHP tag.
Here you have two options. The simple option is:
if (function_exists("register_sidebar")) { register_sidebar(); }
The more complex option is:
if (function_exists("register_sidebar")) { register_sidebar(array( 'name' => 'left-sidebar', 'before_widget' => '<div class="side-widget">', 'after_widget' => '</div>', 'before_title' => '<h2>', 'after_title' => '</h2>', )); }
The complex option gives you the ability to name your sidebar. Here you have “left-sidebar” as your name (just in case you ever want to add a second sidebar). You have also coded what you want to appear before the widget, after the widget, before the widget’s title and after the widget’s title. So now all your widgets will appear on the front end with HTML like this:
<div class="side-widget"> <h2>Widget Name</h2> <em>Widget stuff</em> </div>
You can now style your Widgets to appear how ever you want by creating a style for .side-widget in your style.css stylesheet. You should also create a style for the unordered lists that will appear, since most widgets display text under a list. Add .side-widget ul and .side-widget ul li to you style.css file as well.
Next you need to add some code to your sidebar.php files to make it all functions properly.
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?> <!-- Add your stuff here --> <?php endif; ?>
or
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(1) ) : ?> <!-- Add your stuff here --> <?php endif; ?>
or
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('left-sidebar') ) : ?> <!-- Add your stuff here --> <?php endif; ?>
The above will all do the same thing (but the second and third option are necessary if you have multiple sidebars).
Now all you have left to do is go into your WordPress admin section for your widgets and add some to your sidebar.
29 comments for “How to Widgetize your WordPress sidebar”