WordPress Bits

Hacking WordPress. Keeping the bits together.

Writing WordPress plugin. Widget Loader.

Posted by Leonid Mamchenkov on June 18, 2007

One of the best things about WordPress is its flexibility. For any given problem there are several solutions (“There is more than one way to do it” paradigm at work). There are many places where you can add code and markup – widgets, templates, plugins…

In this post, we’ll look at WordPress plugins. What are they? What can we do with them? How do we write them? We’ll go as far as create our own WordPress plugin from scratch. And it will be a useful one too.

WordPress plugins are simply chunks of PHP code. They are very useful for separating logical pieces of functionality of your web site for easier maintenance and reuse. If you know how to program PHP, you can make your web site do anything you want it to. If you don’t know how to program, you can browse through available plugins (see WordPress plugin directory for example) and choose pieces that suit your needs and wants – usually, installation and configuration of WordPress plugin requires very little technical expertise.

I like thinking about WordPress plugins as bricks. Bricks aren’t very useful or interesting on their own. Similarly, WordPress plugins aren’t of much interest when examined separately from WordPress. But when bricks are put together, when they are mixed with some concrete and architect’s creativity, we can see them emerge into some amazing structures. Similarly, WordPress plugins, when mixed with themes and widgets, can make a web site to really stand out.

Let’s jump into action now. Let’s solve some boring problem with a WordPress plugin. Let’s make something useful. Do you have any ideas yet?

Well, I do. During our widget tutorials, I kept doing the same thing over and over again – registering widgets. For each widget that I want to use for my web site, I had to have this piece of code added to my theme’s functions.php:

Register date widget

It’s a small chunk of code. It’s easy to understand and all. But what happens if I have dozens of widgets that I want to use? My functions.php grows and grows. What happens when I want to use the same widget or two for another web site of mine? I have to do plenty of scrolling, coping, and pasting. This doesn’t sound like a lot of fun. There should be a better way.

What if I could just have a separate file for each widget (which I already have anyway), and what if I could just copy this file somewhere into my theme directory and the widget contained in that file just be available for me in the administration area? That would make my life so much easier!

Can I have it so? The answer is “yes”. “Yes, of course”, even.

I can have a plugin, which, when enabled, would look at a predefined place in my theme, find all widget files, and automatically register them. Let’s starting writing it.

WordPress plugins live in wp-content/plugins/ subdirectory. They can be simple PHP files, or they can have directories and subdirectories, CSS styles, JavaScripts, and images of their own. Like widgets, WordPress plugins can be as simple as a single command, or as complex as a standalone application.

For my plugin, which I decided to call Widget Loader (yes, very creative, I know), I’ll need a single file. No need for a subdirectory or anything like that. Here is how I start my plugin widget_loader.php:

Plugin comment with meta information

WordPress plugins start with a comment, which provides some information about the plugin, which WordPress displays in plugin administration interface. Things like plugin name, version, information about author, license and stuff like that, all go into this comment. (See WordPress Plugin API for more information)

Now we can add PHP code for our plugin. For Widget Loader, all we need is a simple function, which will look for files in widget/ subdirectory of the current theme, and include() them. Here is the code:

Load widgets function

Small and simple. Just the way I like it (see KISS principle). There are a few things to note though:

  • Function name – lm_widget_loader. We want our function name to be as unique as possible, to avoid name clashes with functions from other plugins that we might use on our web site. Here, I’m prepend my initials to the function name.
  • Safety. There is no such thing as too safe when it comes to WordPress plugins. WordPress is a popular application, which runs on a number of platforms, with varying configurations. This brings a lot of potential for things being not exactly as you’d expect them. So, it’s a good idea to check your assumptions – WordPress versions, availability of functions that you rely on, PHP version, filesystem operations, database connectivity, etc. Before using something, check that it’s there and that you have enough rights to use it.
  • Cleanup. With this simple code snippets it doesn’t look like a big problem if you leave something hanging – an open file or directory, an extra database connection, or a large data chunk in memory. But. You should always remember the fact that most WordPress web sites have multiple plugins enabled. When loose ends hang from a dozen plugins, things get ugly. Web sites slow down, error messages pile up, and things get hard to troubleshoot. So, cleanup after yourself.
  • TEMPLATEPATH. WordPress provides plenty of handy functions and variables to make plugin developers’ lives easier. Things can be done the old way (“I’ll write that thing myself.”) or they can be done the WordPress way (there is a function or variable set for everything). It might take you some time and Codex digging to get from one stage to another.

Our plugin is almost done now. In fact, it is a valid plugin, and if you save it in wp-content/plugins/widget_loader.php , you will immediately see it appear in plugin administration interface inside WordPress. Activate it there, and you will be able to use lm_load_widgets() function call from anywhere in your theme or other plugins.

And that is the thing that I don’t really like now. All my widgets are loading just fine, but I have to remember to call lm_load_widgets() from my theme. And what if I give this plugin to somebody who is not very technical? They’ll have to edit their theme files, which can lead to all sorts of problems.

Instead, I want this function to be called automatically. I want WordPress to handle it on its own. It should be smart enough. And, in fact, it is.

WordPress has those things called “hooks“. Hooks are programming interfaces that allow us, programmers, change the way WordPress behaves, but from within our plugins and themes, without the need for editing of WordPress core files. There are two types of hooks – actions and filters. Filters allow us to change WordPress output, such as post title or user comment. (We’ll talk about these in another post later on). Actions allow us to tell WordPress what we want it to do when it gets to a certain point, such as printing comment form, inserting post into the database, or checking user’s credentials.

For our little Widget Loader plugin, we want to tell WordPress to call lm_widget_loader() function whenever it initializes (basically, when it loads all that other stuff and prepares to serve a request). There is a hook just for that. It’s called “init“. (You can see which other hooks are available together with some documentation for them at WordPress Hooks web site.) Here is how we use it:

Function call to add action

That’s it. Just in case you missed or misunderstood something, here is the full text of our wp-content/plugins/widget_loader.php file:

Widget Loader plugin

Once this plugin is activated, we can just drop some widget files into widget/ subdirectory of our theme. To remove a widget, we just delete it from that subdirectory. To edit the widget, we just edit the file. No need to do tonnes of boring copy-paste. Chances of breaking something are even smaller now. And we can easily reuse bits and pieces between different themes and even between different web sites.

We’ll talk more about WordPress plugins in the upcoming posts…

15 Responses to “Writing WordPress plugin. Widget Loader.”

  1. Very nice blog :) and very interesting info’s in here

  2. Thanks Sergios :)

  3. Michel said

    Same as Sergios:

    Nice blog, lots of useful info! :)

  4. Good, good. :)

    This was just the warm-up. To be honest, I’ve learned a lot about widgets by just writing these articles (never did the one with control, for example). But there are quite a few things which I wanted to post from before (plugins, themes, administration area, development-production setup, etc).

  5. Michel said

    Great :-)

    Then I’ll continue reading (and, hopefully, experimenting meanwhile) while you write :-) ;-)

  6. Michel said

    I also’d like to write about a lot of stuff, too… But. But too much work takes all my free time :-(

  7. […] Top Posts Home and the rest of main menu on a WordPress based web siteWordPress webapp framework. More than a blogging engine. More than a CMS.Widgetized web site. Beyond sidebars.Writing WordPress plugin. Widget Loader.About […]

  8. New in 2.3: Importer Plugins

    Eventhough WordPress 2.3 hasn’t yet been released to the general public at the moment I’m writing this, I’d like to do one or more posts on some of the new features that went into 2.3. Although tagging is propably the biggest new addition, everybody…

  9. […] WordPress filter is a type of hook (another type is action hook, which we briefly look at while writing first WordPress plugin). Filters allow data modification on-the-fly. Which means you can change something after it was […]

  10. Great Tutorial. Thanks

  11. Yes, you are right, right mix of plugin with right theme / template can make wordpress a very interesting and useful system .

    Thanks for the Tutorial


  12. Sham said


  13. Mark said

    Thanks for your helpful post. I wonder if you or your readers might be able to answer a plugin question.

    I’d like a plugin to filter out the normal content that occurs in the loop, when activate. Instead it would display the plugin content. I can activate and add my content, but I cannot figure out how to suppress displaying the post, number of comments, categories, etc.

    I’ve tried things like following with no success:
    remove_action(‘the_loop’, ‘hello_world’);
    remove_action(‘the_post’, ‘hello_world’);
    remove_action(‘the_content’, ‘hello_world’);
    remove_action(‘the_title’, ‘hello_world’);
    add_filter(‘the_loop’, ‘hello_world’);
    add_filter(‘the_content’, ‘hello_world’);
    add_filter(‘the_title’, ‘hello_world’);

    I gotta be missing something simple here, right? =)

  14. […] WordPress filter is a type of hook (another type is action hook, which we briefly look at while writing first WordPress plugin). Filters allow data modification on-the-fly. Which means you can change something after it was […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: