WordPress: Hello World Widget

Hello World Widget Area

To add widgets to your theme, you must have or create a ‘widget area’ as a widget placeholder and a widget to add to your widget area.

In the functions.php file of your theme, you can create a custom widget area by using the following code.

if (function_exists('register_sidebar')) {
register_sidebar(array(
'name'=> 'Hello World Widget Area',
'id' => 'hello_world',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<div id="div_hello_world_title">',
'after_title' => '</div>',
));}

Hello World Widget

This simple method does not use the extension of the WP_Widget class, which is the preferred method.
In the functions.php file of your theme, add the following code for the HelloWorld Widget.


function widget_helloworld() {
echo "Hello World!";
}
if (function_exists('register_sidebar_widget')) {
register_sidebar_widget(__('Hello World Widget'), 'widget_helloworld');
}

To add your widget to the dynamic sidebar:
– Go to your WordPress Dashboard > Appearance > Widgets, and
– Drag’n’drop the Hello World Widget to the dynamic sidebar on the right.

Hello World Template

Finally, you need a template to include your widget area. Create a helloworld.php file and include the following code.


<?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Hello World Widget Area')) : ?>
<!-- if widgets are not available -->
<?php endif; ?>

Leave a Reply

Your email address will not be published. Required fields are marked *