Create WordPress Plugins with OOP Techniques

Create WordPress Plugins with OOP Techniques

Tutorial Details
  • Program: WordPress
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 minutes

Object-oriented code, among other things, can help organize and add reusability to your code. In this tutorial, I will teach you the basics of writing a WordPress plugin using object oriented techniques. We’ll be using Dribbble’s API as an example for this tutorial. Ready?


What We’re Going to Learn:

  • Benefits of using OOP for WordPress plugins.
  • How to setup a shortcode.
  • How to setup a template tag.
  • How to enable shortcode in WordPress widgets.
  • Real-world example by using Dribbble’s API.

Why Use OOP?

Before moving forward with this tutorial, you should have at least an elementary understanding of writing a WordPress plugin. Jonathan has written an amazing tutorial on “How to write a WordPress Plugin”. Give it a read.

Creating WordPress plugins with object oriented code is quite efficient and tidy, when compared to using procedural code. It’s easier to manage the code base, and expand it using inheritance techniques, which can be particularly helpful when writing a large plugin.


Dribbble

To write a WordPress plugin, we first need a sense of direction. We’re going to write a plugin that will display the latest shots from Dribbble, using their REST API. We’ll then add shortcode support for posts and widgets, and template tag for themes.


Step 1 - Setting up the Plugin Class

Object oriented code is based on classes and methods (functions). Let’s create our core class, which will interact with WordPress’ hooks and filters.

class WPDribbble {
	public function __construct()
	{
	}
}

$wpDribbble = new WPDribbble();

PHP classes have a constructor function, __construct, which is executed as soon as a new instance of a class is instantiated. All WordPress hooks and filters will be registered under the constructor of our plugin class. Lets push ahead and register a shortcode for our plugin. The add_shortcode() function/hook will go under the constructor function.

The new instance of a class/object is registered using the new keyword. Refer to the last line in the code below.

class WPDribbble {
	public function __construct()
	{
		add_shortcode('Dribbble', array($this, 'shortcode'));
	}
	
	public function shortcode()
	{
	}
}

$wpDribbble = new WPDribbble();
  • add_shortcode – The first parameter is the shortcode tag, and the second is the callback function.

Notice how we’re using an array in the callback function parameter? To register callback functions inside an object, we have to use an array.

The first item of the array references the object, via $this. The second item in the array is the method name within the class. All hooks and filters have to be referenced like this when inside a class.

Still Confused?

# 1. Standard usage
add_shortcode('shortcode_name', 'shortcode_func');

function shortcode_func()
{
 // Contents of this function will execute when the blogger
// uses the [shortcode_name] shortcode.
}

# 2. With PHP 5.3, we can pass an anonymous function.
add_shortcode('shortcode_name', function() {
   // Contents of this function will execute when the blogger
  // uses the [shortcode_name] shortcode.
});

#3. Within a class
class WPDribbble {
	public function __construct()
	{
		add_shortcode('Dribbble', array($this, 'shortcode'));
	}
	
	public function shortcode()
	{
           // Contents of this function will execute when the blogger
          // uses the [shortcode_name] shortcode.
	}
}

Step 2 - Dribbble API Class

Since we currently do not require any fancy API functions, we’re going to create a rather simple API wrapper for Dribbble. There is already a library available for Dribbble, but, for the sake of this tutorial, we’re going to write our own. It’ll help you understand the concepts behind this tutorial.

We’re going to write a DribbbleAPI object, and register a method called getPlayerShots() to interact with Dribbble’s API and return an array of the latest shots.

Let’s create a new file for this class, called DribbbleAPI.php

class DribbbleAPI {
	// url to Dribbble api
	protected $apiUrl = 'http://api.dribbble.com/';
	
	// Dribbble username or user id
	protected $user;
}

Above, we’re setting up two class variables.

  • $apiUrl – The link to the Dribbble API, where the calls will be sent.
  • $user – The username or user id of a Dribbble user. This value will be set from within the constructor (__construct) method.
class DribbbleAPI {
	// url to Dribbble api
	protected $apiUrl = 'http://api.dribbble.com/';
	
	// Dribbble username or user id
	protected $user;
	
	public function __construct($user)
	{
		$this->user = $user;
	}
}

The constructor is passed a $user variable, which is then passed on by the constructor to the class property, called user.

We prefix the property, or variable name with public to specify that the value of this property can be retrieved from outside of the class. If we instead wish to limit access to the property to only this class, and perhaps any classes that inherit from it, we’d use the protected prefix. This practice is referred to as encapsulation.

We have the base ready for our Dribbble API wrapper. Now, We’re going to write a new method, called getPlayerShots(). The purpose of this method will be to query the API and convert the result into an array for usage within our plugin.

class DribbbleAPI {
	// url to Dribbble api
	protected $apiUrl = 'http://api.dribbble.com/';
	
	// Dribbble username or user id
	protected $user;
	
	public function __construct($user)
	{
		$this->user = $user;
	}
	
	public function getPlayerShots($perPage = 15)
	{
		$user = $this->user;
		
		$json = wp_remote_get($this->apiUrl . 'players/' . $user . '/shots?per_page=' . $perPage);
		
		$array = json_decode($json['body']);
		
		$shots = $array->shots;
		
		return $shots;
	}
}

Learn more about wp_remote_get.

The getPlayerShots function retrives the user from the class variable. It uses WordPress’ wp_remote_get function to query the Dribbble API. The API then responds to our query with a JSON string, which is then parsed into an array and sent back to the function using the return keyword.

This is all that we require from the API at the moment – simply an array of player shots. If we happen to require more functionality in the future, we can either add more methods to the current class, or create a new class that extends this one. Again, this is referred to as inheritance.


Step 3 – Integrating the DribbbleAPI Class

This is the fun part; the freshly baked DribbbleAPI class will come into use. We’re going to loop through the shots retrived from the API, and generate an html list of shots, which will be passed on to the shortcode and the template tag. During the loop, the full-sized Dribbble images will be cached and saved in the plugin folder, and the thumbnails will be generated using TimThumb.

To determine if the full images are already stored locally, the plugin path is required. Also, to generate the thumbnails with timthumb, the plugin url is required. For this purpose, we’ll create two class variables called pluginPath and pluginURL in our WPDribbble class, and then set their values from within the constructor method.

Setting PluginPath and PluginUrl

class WPDribbble {
	protected $pluginPath;
	protected $pluginUrl;
	
	public function __construct()
	{
		// Set Plugin Path
		$this->pluginPath = dirname(__FILE__);
	
		// Set Plugin URL
		$this->pluginUrl = WP_PLUGIN_URL . '/wp-Dribbble';
		
		add_shortcode('Dribbble', array($this, 'shortcode'));
	}

getImages() Method

Create a new method within the WPDribbble class, called getImages.

Inside a class, you can use generic names for functions. They will not conflict with other plugins or WordPress’ built-in functions, because they are under the class namespace.

public function getImages($user, $images = 3, $width = 50, $height = 50, $caption = true)
{
}
  • $user – Username or User ID of Dribbble. $user will be used when registering a new instance of the DribbbleAPI class.
  • $images – Number of images to render. $images will be used when querying the API through the getPlayerShots method.
  • $width and $height – Timthumb will be used to generate thumbnails.
  • $caption – Option to render title of an image.

Next, we’re going to include the DribbbleAPI class in the getImages() function, and create a new instance of it to grab the images.

public function getImages($user, $images = 3, $width = 50, $height = 50, $caption = true)
{
	include 'DribbbleAPI.php';
	
	$DribbbleAPI = new DribbbleAPI($user);
	$shots = $DribbbleAPI->getPlayerShots($images);
	
	if($shots) {
	}
}

The $shots variable in the code is populated with an array of three recent Dribbbles from the $user.

As mentioned previously, we’re going to loop through the $shots array, and save the full size images locally for caching purposes. The cached images will be used with TimThumb to serve the thumbnails. For storing full-images and thumbnails generated by TimThumb, create two folders. We’ll use full-images/ for storing the full size images, and cache/ for the thumbnails, since that is the default folder name for TimThumb.

The HTML for the list will be generated within the $shots loop.

public function getImages($user, $images = 3, $width = 50, $height = 50, $caption = true)
{
	include 'DribbbleAPI.php';
	
	$DribbbleAPI = new DribbbleAPI($user);
	$shots = $DribbbleAPI->getPlayerShots($images);
	
	if($shots) {
		$html[] = '<ul class="wp-Dribbble">';
		
		foreach($shots as $shot) {
			$image = $shot->image_url; // url of the image
			$fileName = $shot->id . '.png'; // generating a filename image_id.png
			
			if (!file_exists($this->pluginPath . '/full-images/' . $fileName)) { // check if the full image exists
				$rawImage = wp_remote_get($image); // get the full image
				$newImagePath = $this->pluginPath  . '/full-images/' . $fileName;
				$fp = fopen($newImagePath, 'x');
				fwrite($fp, $rawImage['body']); // save the full image
				fclose($fp);
			}
			
			// generate thumbnail url
			$localImage = $this->pluginUrl . '/timthumb.php?src=' . strstr($this->pluginPath, 'wp-content') . '/full-images/' . $fileName . '&w=' . $width . '&h=' . $height . '&q=100';
			
			if($caption) { // if caption is true
				$captionHTML = '<p class="wp-Dribbble-caption">' . $shot->title . '</p>';
			}
			
			// combine shot url, title and thumbnail to add to the ul list
			$html[] = '<li class="wp-Dribbble-list"><a href="' . $shot->url . '" title="' . $shot->title . '"><img src="' . $localImage . '" alt="' . $shot->title . '" /></a>'.$captionHTML.'</li>';
		}
		
		$html[] = '</ul>';
		
		return implode("\n", $html);
	}
}

Adding Classes

It’s always a good idea to add classes to each element of your plugin. This provides the advanced users of your plugin with the freedom to customize it. Avoid using inline CSS for content that is generated through your plugin.


Step 4 – Setting up the Shortcode

Shortcodes, as the name suggests, allows users to easily add complex content into blog posts.

We already have the add_shortcode hook ready in our plugin class constructor. Now, we’re going to write the shortcode method inside our class, which will exract the shortcode attributes and return the Dribbble images by using the getImages() method.

We’ll be calling our shortcode [Dribbble]. As mentioned previously, the name of the shortcode is determined by the first parameter in the add_shortcode function. It will be used with the attributes required for the getImages() method. For example: [Dribbble user=haris images=5 width=100 height=100 caption=true].

public function shortcode($atts)
{
	// extract the attributes into variables
	extract(shortcode_atts(array(
		'images' => 3,
		'width' => 50,
		'height' => 50,
		'caption' => true,
	), $atts));
	
	// pass the attributes to getImages function and render the images
	return $this->getImages($atts['user'], $images, $width, $height, $caption);
}

Add Shortcode support for WordPress Widgets

By default, WordPress widgets don’t support shortcodes, however, by using the widget_text filter, we can force shortcode support in WordPress widgets.

We can add the filter in our WPDribbble object constructor.

public function __construct()
{
	// Set Plugin Path
	$this->pluginPath = dirname(__FILE__);

	// Set Plugin URL
	$this->pluginUrl = WP_PLUGIN_URL . '/wp-Dribbble';
	
	add_shortcode('Dribbble', array($this, 'shortcode'));
	
	// Add shortcode support for widgets
	add_filter('widget_text', 'do_shortcode');
}

Step 5 Setting up the Template Tag

The template tag can be used directly in WordPress themes. The basic purpose of the template tag will be to create a new instance of our WPDribbble class, and call the getImages() method. The template tag will be a simple PHP function and it has to be registered outside the plugin class. It needs to have a unique name; otherwise, it will conflict with functions / plugins with similiar name. Since our plugin is called WP-Dribbble, we’ll call the template tag, wp_Dribbble().

function wp_Dribbble($user, $images = 3, $width = 50, $height = 50, $caption = true)
{
	$wpDribbble = new WPDribbble;
	echo $wpDribbble->getImages($user, $images, $width, $height, $caption);
}

Voila!

Congratulations! You have successfully written a WordPress plugin with OOP. If you have any questions, let me know, and I’ll do my best to help you. .

Tags: Wordpress
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://nvmind.com Ignacio

    Very useful and easy to follow tutorial, thanks Muhammad

  • TheSpawn

    Interesting, I’ll try it ASAP and I’ll let you know! Good job!

  • Sebrosen

    Great tutorial!

  • http://insfired.com S.K. (Insfired)

    This is very well-detailed and laid out. Impressive work Muhammad!

  • http://www.hostalia.com Hosting

    Sound good this post for create my own plugins.

  • http://www.BlaineSch.com BlaineSch

    Great job at explaining the process! We should have more WordPress articles!

  • http://galengidman.com Galen Gidman

    Dribbble is spelled with 3 ‘b’s guys… ;)

    • http://mharis.net Muhammad Haris

      Hehe, yeah, 3 b’s. :)

  • http://jakswebdesign.com Adam

    This is going to be the latest craze amongst wordpress-only coders – those who can write “WordPress” PHP, but can’t write it elsewhere.

    Don’t declare your class properties as public unless you have very good reason to. In the example above, all of the properties, and some of the methods should be PRIVATE.

    • http://mharis.net Muhammad Haris

      Completely valid. All class properties are public in the tutorial.

      When writing your own plugin, do play around with public and private class properties. It adds more semantic value and protection to your code.

    • neil

      It never seizes to amaze me how often people who use this site NIT PICK on other peoples tutorials. If anyone has even attempted to write one themselves then you will at least understand how difficult it can be and appreciate them a bit more!.

      Superb tutorial Muhammad, i look forward to many more?

      • Bob Brown

        Nit picking would be non-existent if people substantiated their claims with actual reasons as to why you shouldn’t do one thing over another.

        At least educate the people with an example as to why, because comments that include additional explanations that further explain your objections can actually compliment and improve the overall quality of tutorials like this by promoting open discussion towards best practices.

    • Kevin

      Agreed, really not a good example of OOP. It would be a shame if people went away from this thinking they know OOP as they would have a false sense of security. If the Tutorial states OOP techniques then I would have liked those techniques identified. Using a class in my book does not qualify as OOP.

      @neil Criticism backed up with explanation should form the basis of progression to better tutorials. If we all went round saying how wonderful everything is, stroking each others egos, then that would be pathetic.

  • http://prop-14.com Randy

    Very nice. My first OOP code was for dynamically creating PayPal “add to cart” buttons for a product custom post type. I really began to see the benefit of using OOP.

  • http://pippinsplugins.com Pippin

    I understand the benefit of OOP in regards to possible function conflicts and such, but is there really any other advantage? I’m sure there is, I just don’t really know what it is. Can you give another reason why it’s better?

    • http://mharis.net Muhammad Haris
      Author

      Hi Pippin,

      It adds organization and reusability to the code. If you’re a regular plugin author, you can create classes for your regularly used functions such as creating menus in wp-admin. Although it is not hard to create a few lines of code over and over again for creating menus in wp-admin but creating classes like that will reduce number of lines per code which will also affect the time spent on writing a piece of function.

      • http://www.johnciacia.com John

        As an addendum, it adds a sort-of “namespace” to your code. A lot of novice developers use generic function names like “shortcode” or “install” which can quickly lead to function redefined issues.

      • فیلم
  • arnold

    make WordPress plugin dev screencast…please

  • http://www.arnaud-olivier.fr Arnaud

    Thanks!:) i look at this

  • bohuslav_rodich

    Hi there…Thanks for the posts. I have pleny of wonderful templates, but have no idea how to generate them to WordPress environment..I need help urgently! I know there are multiply tools for psd publishing, but the one need must have friendly interface and be of high functionality…Thanks to all

    • claude_jenaur

      hello! i publish psd templates to wordpress with Divine Elemente pluign (for photoshop). if there is no coding experience, this might be one of the best choices. try it.

  • kevin

    Not the best example of OOP. No real explanation of inheritance, member variable scope. More of a tutorial on encapsulating wordpress plugin authoring using a class.

    • http://jakswebdesign.com Adam

      Be careful Kevin, I tried to state the fact that the author was playing fast and loose with OOP in a comment above and Neil thought I was just being “NIT PICK”y.

      At the very least I think this article deserves a link to a resource the explains what classes and objects are and how and when one should (and shouldn’t) use them.

      • Neil

        @Adam, it just amazes me how those that use this site to learn things, end up being more knowledgeable then the teacher! This tutorial is called ‘Create WordPress Plugins with OOP Techniques’ not ‘ How to learn OOP and then create a wordpress plugin’

        Constructive Criticism is great, but showing no appreciation for the writers efforts and leaving comments that only make the writer look noobie, is in my mind NIT PICKING! I have been using this site for years and half of the comments that writers recieve are exactly that. At the very least comments should show some appreciation…..

        ‘Thanks for the tutorial Muhammad, but you might wanna look at NOT declaring your class properties as public unless you have very good reason to. In the example above, all of the properties, and some of the methods should be PRIVATE. – but thanks again, your my Hero!’

        Or am i just NIT PICKING?

  • http://www.todaytricks.com/ David Villa

    Very Informative tutorial Muhammad.I appreciate your effort on this tutorial.thanks for sharing.

  • w1sh

    Nice tutorial, but what happened to Giles Python series? :\

  • http://www.jblotus.com james fuller

    I stopped reading your article after a few sentences because you didn’t bother to spell dribbble correctly. That made me think the rest of your article would also be lacking in quality and attention to detail.

    • http://powerpointz.com Amanda

      Well you’re gonna have a hard time in this planet, since nothing here is perfect.

    • surefoot

      Did you actually check http://dribbble.com/? This is a actual site.

    • Bob Brown

      You’re taking the piss, right?

      After reading your blog, I would have thought you were more of a constructive contributor than criticizer.

      Instead if you’re going to critique something, how about critiquing his code? You know, something to say of real benefit.

      Imagine if your IDE thought the same thing to itself every time it goes to parse your code and you misspell a class, function, variable name or perhaps miss some closing parenthesis?

      “pffff not parsing this dudes code anymore…rest of code must be lacking in quality and attention to detail” – Sincerely yours, IDE.

  • http://tintation.com Vladimir

    Good and useful article post :)
    Thanks for sharing.

  • http://soderlind.no PerS

    Very nice article. I like the OOP approach and have created a plugin creator that creates a OOP based plugin template. You can test it at my site: http://soderlind.no/wordpress-plugin-template-creator/

  • http://www.carOSHA.com CarlosJa

    Pretty cool tutorial. I’ll have to give it a try

  • José Gómez

    i have a question, why you don’t extends the API Class to the main class? i think it will be better, and have, and of course, writing it in just one file.

  • Peter South

    I know that writing OO code in a WordPress context is quite hard, because WordPress itself is using only very limited OOP techniques. Maybe I can provide some hints for improvement.

    Don’t use public attributes if not necessary (it’s not necessary in this case, getters/setters can easily be implemented). Don’t use include inside the methods. By doing so, you’re creating an invisible dependency (only visible to those who read the class code, which should not be necessary if you just want to use the public api). And if getImages() is called twice, the DribbbleAPI is included twice, so an include_once or require_once might be better.

    The getImages() method is very long. You put some comments inside that method, which is good. Try using those to extract code blocks into some private methods to shrink the method’s size. Also try to separate the html from business logic.

    It’s a good thing you started with OOP, keep it up and you’ll notice that OOP is much more than putting code into classes :-)

  • http://www.sonnydesign.com sawebdesigns

    Now this i like create your own plugins

  • Сarlos

    To claude_jenaur, why are you posting this here? this thread for a plugin creation, not for psd to wordpress, right? but, to be honest, i’ve been so curious and googled this plugin http://www.elemente.divine-project com this is what you talking about? and have to admit it does the job. need to test it further”

  • http://www.adsgah.com آگهي رايگان

    brilliant tutoria.thnx a lot

  • http://dropwall.com Chris

    This is a really great tutorial! Learning about shortcodes and writing a wordpress plugin with oop techniques with a real world example (Dribbble) is just awesome, thank you!

  • Fabrizio

    Hi Muhammad,

    thanks for this interesting tutorial. I would like to ask you a question about the getImages function. Shouldn’t it use an “include_once” for the file “DribbleAPI.php” instead of “include”, in order to not throw errors if the shortcode or the template tag is used twice in the same request?

    Fabrizio

  • http://smsay.tk vico

    i’m confused …… :D

  • http://bcooling.com.au Global

    Just thought I would let you guys know it appears this article by Nettuts has been stolen by this website: http://www.ideascart.com/learn/create-wordpress-plugin-using-oop-techniques/

  • Jagdeep

    Hi Muhammad,

    Thanks for this tutorial. It is really very helping for wordpress and oops beginners. As it have a real word example to developed a wordpress plugin using oops.

    JS Banga

  • Rajesh Singh

    This is one of the best answer so far, I have read online. No crap, just useful information. Very well presented. I have found another good collection of wordpress article which also explained very well, check out this helpful link…
    http://mindstick.com/Articles/d2429576-497d-4a9f-97fd-4053d0c08a17/?Creating%20Plugin%20in%20WordPress

    Thanks everyone for your nice post.

  • http://erhanabay.com Erhan
  • Robes

    Best tut!

  • http://www.acousticdampingfoam.net Josh

    Great post. It was very helpful!

  • http://fatburningfurnacel.com Miah

    So the benefits of using OO is just for large plugin? For very simple plugin I believe it’s still faster to use procedural.

  • http://zce.me webarto

    @Miah, no, you should use object oriented code always. Unfortunately, whatever you do in WordPress, it isn’t OOP. It is just lookalike. Class in example is just set of methods (functions). No mean to offend author. It is better than procedural in every way.

  • shoaib

    how i can use this plugin…. i followed it line by line now whats next how i can use this plugin any help :(

    • http://roes-wibowo.com Roes Wibowo

      I tried to install and activate this plugin but it doesn’t work too..

      • zarkod

        I have the same problem…

  • http://roes-wibowo.com Roes Wibowo

    Any reference for shortcut function wordpress cms such us “add_filter(”);” ect? WordPress codex isn’t enough useful for development… :(

  • Jalal Khan

    Great tutorial…………… thanks Harris Bhai

  • Anonymous

    Just thought I would point out that if anyone is going to try to re-use the source files included in this article, please update TimThumb to the latest version, as the one included is vulnerable to PHP injection.

  • http://tallytree.com Aras

    Awesome tutorial Muhammad! It helped me a lot in understanding how to write my plugin using object oriented code from the begining. Thanks!

  • http://www.wpformarketers.com Matt

    Yes great tutorial, Muhammad. As some have pointed out, it’s not exactly full-blown OOP, but like Neil says as a tutorial for using OOP techniques to write a WordPress plugin this is very well put together! Easy to follow and explains just enough to give a basic understanding and make people want to try it out.

    Also, @Peter South, very good points and positive criticism is a good way to bring them up.

  • http://techntechie.com Himadri

    Do you know that there is one new plug in available in wordpress and it is named as WordPress Liveblog plugin…What is your comment about this?Bloggers are telling that it is having some bugs.I also experienced.But it is easy to post live news using this plugin.I have posted it in technology news you can check.

  • Rasel khan

    Please link me your PSD-to-WP video tutorials series……

  • Not Alan Kay

    You’ve used OOP to namespace your functions and pass them to the same procedural code WordPress would have otherwise used. It’s the difference between:


    function x() {
    print "my module";
    }
    wp_hook('x');

    and


    class my_module {
    public function __construct() {
    wp_hook(array($this, 'x'));
    }
    public function x() {
    print "my module";
    }
    }
    $mymodule = new my_module();

    The resulting code isn’t any cleaner, clearer, or more portable. This isn’t your fault – it’s developers who in an effort to “make WP more OOP” have missed the boat entirely. When WP plugins inherit some kind of base Plugin class and override its methods to implement their functionality then we’ll be using OOP methods to create plugins.

  • francis

    can you help me create a signature of single post plugin using oop