Fun with Theme Widgets

Following on from my post about Widget Management Concepts, I have produced a new plugin with the aim of making it super easy to include widgets within themes without needing to be concerned with writing plugins, or code in functions.php.


To install the plugin just download it and activate it. It has no options.

Creating Theme Widgets

Creating a theme widget really is very easy. Here is a step by step process.

Step 1

Create a new PHP file in the theme and call it {something}.widget.php.

Step 2

Add a PHP comment at the top of the file to indicate the name and description of the widget. Like this:

Widget Name: 3 Random Posts
Widget Description: Outputs 3 random posts in a list

Step 3

Add the code you want for your widget. In this example I am adding code to output three posts at random:

<?php $postslist = get_posts('numberposts=3&order=ASC&orderby=rand'); ?>
<?php foreach ($postslist as $post) : ?>
	<?php setup_postdata($post); ?>
	<strong><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></strong><br/>
	<?php the_excerpt(); ?>
 <?php endforeach; ?>

Note that this code is identical to the code you would insert into a theme file to do this manually. There is nothing special about this code that needs to be changed to make it a widget.

Step 4

Assign the widget to sidebar.

On the left of the image is the output (there is only one post because it is a fresh installation) on the right the widget added to the sidebar.


You can download the plugin from WordPress extend.

The Potential

I think that making it this easy to create, and more importantly understand, the widgets included with a theme opens up a lot of possibilities. For example, with this it would be easy to use a sidebar and widgets to offer different layouts for a featured post on the home page.

If you have any suggestions for improvements to the plugin itself, or ideas about how it can be used, let me know.