My first plugin – one didn’t quite work

April 16, 2007

I was trying to figure out how plugin is done. First obvious step would be looking at plugins that came with the download. There are 3 of them, namely ‘commentfilter’, ‘spamchecker’ and ‘wpimport’. I firstly looked at their structure. They all look pretty much the same as below:

class MyPlugin extends Plugin
function info[]
return array [
'name' => 'MyPlugin',
'url' => '',
'author' => 'sfong15',
'authorurl' => '',
'version' => '0.1',
'description' => 'Show recent comments',
'license' => 'no such thing',
public function action_plugins_loaded[]
function DoSomething[] {
...code here...

The purpose of the function ‘info’ is obvious it provides information required by the activation interface. I don’t know what ‘action_plugins_loaded’ actually does as the line for ‘Utils’ has been commented out. The purpose of function(s) at the end is also obvious as they actually do something. That could return something as output or act as filters. Writing simple function like that is what beginner like me can do.

You look at the sidebar you’ll see I hard coded ‘recent comments’. That wasn’t difficult as I could ‘borrow’ codes from the ‘admin’ interface. Transforming those to that function ‘DoSomething’ was also a piece of cake.

The final hurdle was calling this function in the posts.php. I looked around but couldn’t find an example as other plugins were used as filters. I then realize there was some basic thing that I didn’t have. That is the OOP part of PHP5. That is something that I didn’t have to learn in WordPress.

The first line of the plugin file class MyPlugin extends Plugin tells me that MyPlugin is a extended class of a base or generic class ‘Plugin’. An explanation of keyword extends is here and simple examples are here. Now I can call the function like this

$obj=new MyPlugin;

I believe the base ‘Plugin’ class is there to make this happen.

Once this is understood then I can use a Scope Resolution Operator ‘::’ to call the function in a much simplified way such as MyPlugin::DoSomething();

All is well but why my first plugin didn’t quite work I really don’t know. As you can see recent comments are shown in a unordered list but the comment url, name etc are also displayed, in fact duplicated outside the ‘ul’ tags, in a string. I have checked and checked a few times and found that string was actually produced outside the function.

I’m clueless at the moment so bug hunt goes on.


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: