WordPress plugin best practices

Author: Lee Aplin

We like to keep our code neat. Who doesn’t? But when building WordPress plugins it can be easy to fall into negative patterns which lead to hard-to-read, or even buggy code. For instance, if two plugins call a function called “get_user_info” for example, a conflict will occur.

So we’re working on a set of best pracitces for developing our plugins. This means applying Object Oriented Programming principles – which aren’t fully integrated into PHP and WordPress, but are usable to an extent – to build structured, sensible code that deals in “objects”.

So we start by putting the main bulk of our code in a class, say PluginClass, and hooking into WordPress’ functionality with code like this:

class PluginClass {
public function __construct() {
add_action('admin_menu', array(&$this, 'admin_menu'));

public function admin_menu() {
// Our function for adding to the WordPress dashboard menu

Because we’ve enclosed our admin_menu function in a class, it doesn’t matter if another plugin uses the same function name.

We further separate user-interface elements like settings pages from the code. This is quite alien in WordPress, which often advocates putting chunks of PHP code in HTML templates. By keeping fragments of pages in another folder and referring to them in our PluginClass object, we can structure our code to make it much more readable and adaptable.

There’s lots more we’re doing, and this set of practices is growing with each new plugin we develop, but this will give you a brief of what we’re aiming at. If you want to know any more or you’ve got a better idea, drop us a comment!