Home » Internet » Web Designing » How to make your WordPress theme widget friendly

How to make your WordPress theme widget friendly



Widgets in WordPress are a great way of adding new functions to your theme extremely fast. When you have a widget friendly WordPress theme you just need to go to your admin area, and then to the widgets section, in order to add stuff to your side bars. There are some common tasks in WordPress for which you don’t have to write even a single line of code and they can be achieved by simple drag and drop.

Making your WordPress theme widget ready involves very small changes to your sidebar section, and a theme file called functions.php – this file should be present in your theme directory: /wp-content/themes/your-current-theme/functions.php

If this file is already there then you need to download it in order to make changes. If it’s not there you can simply create it using your favorite text editing software. To this file add the following code:

<?php
if ( function_exists(‘register_sidebars’) ) {
        register_sidebars(2, array(‘name’=>’sidebar %d’,
        ‘before_widget’ => ‘<div class=”widget”>’,
        ‘after_widget’ => ‘</div>’,
        ‘before_title’ => ‘<h2>’,
        ‘after_title’ => ‘</h2>’,
        ));
}
?>

register_sidebars(), as you can see, has two parameters, the number of sidebars you need to register, and array that tells how the widget should look. “sidebar %d” means you’ll have “sidebar 1”, “sidebar 2” and so on. It can also be “foo %d”, so you’ll have “foo 1” and “foo 2”.

In the side bar of your WordPress theme, you use the following code to invoke the widget:

<?php if ( !function_exists(‘dynamic_sidebar’) || !dynamic_sidebar(‘sidebar 1’) ){?>
<?php echo “No widget!”;} ?>

the dynamic_sidebar() contains “sidebar 1” for the first side bar. For the second side bar it will naturally be “sidebar 2”.

The if condition is used to take care of what happens if a dynamic, widget-enabled side bar does not exist. Here, I have used a message that displays “No widget!”. You can have whatever alternative (some side bar content) you feel like.

And what if you want to register just one side bar? Instead of register_sidebars() you use register_sidebar() and you can use a static name for your side bar, something like:

<?php
if ( function_exists(‘register_sidebar’) ) {
        register_sidebar(array(‘name’=>’my sidebar’,
        ‘before_widget’ => ‘<div class=”widget”>’,
        ‘after_widget’ => ‘</div>’,
        ‘before_title’ => ‘<h2>’,
        ‘after_title’ => ‘</h2>’,
        ));
}
?>