on Writings, Tutorials, CMS, WordPress, PHP

Make better WordPress plugins

This is a short tutorial to show you a basic way to create an object oriented WordPress plugin. We'll be making the simplest of Hello World plugins - it was actually the first class I made to when creating a WordPress plugin with use of object oriented programming. 


Step 1: Create the plugin file

First of all, create a new folder called hello_world within the following directory: your-site/wp-content/plugins. Within the new hello_world folder (your-site/wp-content/plugins/hello_world) create a new file called hello_world.php. When WordPress starts up, it will find this file when it looks through all the plugin folders automatically. 


Step 2: Create the Class

Inside hello_world.php, and paste in the following code:

class Hello_World{

    //instantiate new class
    public static function init() {
        $class = __CLASS__;
        new $class;
    }

    //use constructor to kickstart things
    public function __construct() {

        $this->hello();

    }

    public function hello(){

        echo 'Hello World';

    }

}

This is our Hello_World class, consisting of three functions. The first one, init(), is used to activate the plugin - you'll se how later. The second function __construct() is called automatically, as long as the plugin is active. All __construct does is call the hello() function, which writes out "Hello World".


Step 3: Create the plugin activation hook

Now, just below the class, paste this in:

add_action( 'plugins_loaded', array( 'Hello_World', 'init' ));

In the add_action function, we have specified the hook we want to use: plugins_loaded. This hook is run by WordPress on all active plugins when WordPress starts up. The second parameter of add_action, we pass an array consisting of our class name, and the function we want to run. Our class is Hello_World, and we run the init function - which triggers everything else off.

Now if you open the admin dashboard and look ath the plugins list, you'll be able to activate the hello world plugin. Just make sure you've added all the necessary WordPress comments to the top of the file:

/**  
 * @package Hello_World
 * @version 1
 */
/*
Plugin Name: Hello World  
Description: Hello world description  
Author URI: Anonymous  
*/

That’s really all there is to it, otherwise your code is just a regular class.