March 14, 2008

Table of contents for What I learned while building a WordPress Plugin

Things I’ve Learned While building a WordPress Plugin

After building my first few WordPress plugins I learned quite a few things that I just could not find good information on. So what I will be doing over a couple or so posts is explaining what the problem/issue was that I had and show you how I went about resolving the problem/issue.

How do I add a sub menu for my plugins admin and what is a “unique identifier”?

Ok, creating a submenu is not very hard and WordPress docs does an ok job of explaining it. But when you are building your plugin using a class structure it is not very clear what you should do.

Lets assume that you have a class called “myClass” and a function with in it that is called “adminMenu.” Let’s also assume that this class is also on the same file that is your main plugin file that has the version information on it. Your typical php4 based class would look like (php5 based classes have __construct instead of calling myClass and some other minor differences):

At line three we add an action that points to the “adminMenu” function and let me clarify what I have found happens with “array(&$this, ‘adminMenu’)”. WordPress will take “array(&$this, ‘adminMenu’)” and make it into myClass::adminMenu() and execute it like that – the &this is a reference to myClass.

At line 8 we have the main link that gets put at the top next to “Plugins,” “Comments” and so on. You will notice the __FILE__ constant, this allows WordPress to set that menu item to reference the plugins main file. You also see array(&$this, ‘adminSubPage1′) will execute as myClass::adminSubPage1() (this function is not shown).

At line 11 we create our first submenu for our plugin which also points to the adminSubPage1 function, which is needed I found. If you don’t have a submenu item that points to the same “page” as the main menu item, the submenu items will not show up.

At line 12 we create our second submenu item that points to the adminSubPage2 function (also not shown). You will notice a three differences between the two submenus, two being the Names and the function they point to, and the third is the mc_adminSubPage2 which is our unique identifier. This will give us a url the looks something like admin.php?page=mc_adminSubPage2.

Nothing real fancy with this one, just wanted show how to create your plugin menu items while using a Object Oriented approach. Feel free to let me know if there is an easier way or if I am all around incorrect. Next post will be about loading of jQuery and your other JavaScript without messing up the Prototype code that WordPress and other WP plugins use.