Advertisement
  1. Code
  2. WordPress

Create WordPress Plugins With OOP Techniques

Scroll to top
10 min read
12

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 set up a shortcode
  • How to set up a template tag
  • How to enable shortcode in WordPress widgets
  • Real-world example using Dribbble's API

By the way, if this sounds too advanced and you're just looking for some ready-made plugins that you can download and use on your site, check out our free course on the best WordPress plugins to use for SEO, backup, security, and more.

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 which will display the latest shots from Dribbble, using their REST API. We'll then add shortcode support for posts and widgets, and a template tag for themes.

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.

1
<?php
2
class WPDribbble {
3
    public function __construct()
4
    {
5
    }
6
}
7
 
8
$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. Let's 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 is registered using the new keyword. Refer to the last line in the code below.

1
<?php
2
class WPDribbble {
3
    public function __construct()
4
    {
5
        add_shortcode('Dribbble', array($this, 'shortcode'));
6
    }
7
     
8
    public function shortcode()
9
    {
10
    }
11
}
12
 
13
$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.

Thus, whenever the Dribbble shortcode needs to be executed, it will call the shortcode method of the WPDribbble class.

Still Confused?

1
<?php
2
# 1. Standard usage

3
add_shortcode('shortcode_name', 'shortcode_func');
4
 
5
function shortcode_func()
6
{
7
 // Contents of this function will execute when the blogger

8
// uses the [shortcode_name] shortcode.

9
}
10
 
11
# 2. With PHP 5.3, we can pass an anonymous function.

12
add_shortcode('shortcode_name', function() {
13
   // Contents of this function will execute when the blogger

14
  // uses the [shortcode_name] shortcode.

15
});
16
 
17
#3. Within a class

18
class WPDribbble {
19
    public function __construct()
20
    {
21
        add_shortcode('Dribbble', array($this, 'shortcode'));
22
    }
23
     
24
    public function shortcode()
25
    {
26
           // Contents of this function will execute when the blogger

27
          // uses the [shortcode_name] shortcode.

28
    }
29
}

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

1
<?php
2
class DribbbleAPI {
3
    // url to Dribbble api

4
    protected $apiUrl = 'https://api.dribbble.com/';
5
}

In the DribbbleAPI class, we're setting up the following class variable:

  • $apiUrl: The link to the Dribbble API, where the calls will be sent.

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. In our case, we've defined the $apiUrl property as a protected property.

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.

1
<?php
2
class DribbbleAPI 
3
{
4
    // url to Dribbble api

5
    protected $apiUrl = 'http://api.dribbble.com/';
6
     
7
    public function getPlayerShots(int $user, int $perPage = 15) : array
8
    {
9
        $json = wp_remote_get($this->apiUrl . 'players/' . $user . '/shots?per_page=' . $perPage);
10
         
11
        $array = json_decode($json['body']);
12
         
13
        $shots = $array->shots;
14
         
15
        return $shots;
16
    }
17
}
Learn more about wp_remote_get.

The getPlayerShots method has two arguments. The first argument is the user-id, which will be used in the API URL, and the second argument is the limit value, which will be used to paginate records.

The getPlayerShots method uses WordPress's 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 with the help of the json_decode function 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.

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 retrieved 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 the Imagine library. You can go through the documentation and install it as per the instructions. You can also use your choice of image-processing library to generate thumbnails—you'll just need minor tweaks in the getImages method.

To determine if the full images are already stored locally, the plugin path is required. Also, to generate the thumbnails with the Imagine library, 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.

We will also create the dribbbleApiObject variable to hold the DribbbleAPI object, which we can later use in the getImages method. It's important to note that we have to pass the DribbbleAPI object when we instantiate the WPDribbble class.

Setting Class Variables

1
<?php
2
class WPDribbble {
3
    protected $pluginPath;
4
    protected $pluginUrl;
5
    protected $dribbbleApiObject;
6
     
7
    public function __construct(DribbbleAPI $dribbbleApiObject) : void
8
    {
9
        // Set Plugin Path

10
        $this->pluginPath = dirname(__FILE__);
11
     
12
        // Set Plugin URL

13
        $this->pluginUrl = WP_PLUGIN_URL . '/wp-Dribbble';
14
        
15
        // Init DribbbleAPI Object

16
        $this->dribbbleApiObject = $dribbbleApiObject;
17
         
18
        add_shortcode('Dribbble', array($this, 'shortcode'));
19
    }
20
}

The 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's built-in functions, because they are under the class namespace.
1
public function getImages($user, $images = 3, $width = 50, $height = 50, $caption = true)
2
{
3
}
  • $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 - Imagine will be used to generate thumbnails.
  • $caption - Option to render the title of an image.

Next, we're going to include the DribbbleAPI class in the WPDribbble plugin file, so that we can create a new instance of it to grab the shots.

1
...
2
require_once __DIR__ . '/DribbbleAPI.php';
3
...

Next, let's create the instance of the DribbbleAPI class when we instantiate the WPDribbble class.

1
...
2
...
3
$wpDribbble = new WPDribbble(new DribbbleAPI());
4
...
5
...

As mentioned previously, we're going to loop through the $shots array and save the full-size images locally for caching purposes. For storing full-size images and thumbnails generated by Imagine, create two folders. We'll use full-images for storing the full-size images, and cache for the thumbnails.

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

1
public function getImages(int $user, int $images = 3, int $width = 50, int $height = 50, bool $caption = true) : string
2
{    
3
    $shots = $this->dribbbleApiObject->getPlayerShots($user, $images);
4
     
5
    if($shots) {
6
        $html[] = '<ul class="wp-Dribbble">';
7
         
8
        foreach($shots as $shot) {
9
            $image = $shot->image_url; // url of the image

10
            $fileName = $shot->id . '.png'; // generating a filename image_id.png

11
            $thumbFileName = 'thumb_' .$shot->id . '.png';
12
            $destThumbFilePath = $this->pluginPath . '/cache/' .  $thumbFileName;
13
             
14
            if (!file_exists($this->pluginPath . '/full-images/' . $fileName)) { // check if the full image exists

15
                $rawImage = wp_remote_get($image); // get the full image

16
                $newImagePath = $this->pluginPath  . '/full-images/' . $fileName;
17
                $fp = fopen($newImagePath, 'x');
18
                fwrite($fp, $rawImage['body']); // save the full image

19
                fclose($fp);
20
            }
21
             
22
            // generate thumbnail url

23
            $imagine = new \Imagine\Gd\Imagine();
24
            $image = $imagine->open($newImagePath);
25
            $thumbnail = $image->thumbnail(new Imagine\Image\Box($width, $height));
26
            $thumbnail->save($destThumbFilePath);
27
            $destThumbURL = $this->pluginUrl . '/cache/' .  $thumbFileName;
28
             
29
            if($caption) { // if caption is true

30
                $captionHTML = '<p class="wp-Dribbble-caption">' . $shot->title . '</p>';
31
            }
32
             
33
            // combine shot url, title and thumbnail to add to the ul list

34
            $html[] = '<li class="wp-Dribbble-list"><a href="' . $shot->url . '" title="' . $shot->title . '"><img src="' . $destThumbURL . '" alt="' . $shot->title . '" /></a>'.$captionHTML.'</li>';
35
        }
36
         
37
        $html[] = '</ul>';
38
         
39
        return implode("\n", $html);
40
    }

Adding Classes

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

4. Setting Up the Shortcode

Shortcodes, as the name suggests, allow users to easily add complex content to 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 extract 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].

1
public function shortcode($atts)
2
{
3
    // extract the attributes into variables

4
    extract(shortcode_atts(array(
5
        'images' => 3,
6
        'width' => 50,
7
        'height' => 50,
8
        'caption' => true,
9
    ), $atts));
10
     
11
    // pass the attributes to getImages function and render the images

12
    return $this->getImages($atts['user'], $images, $width, $height, $caption);
13
}

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.

1
public function __construct(DribbbleAPI $dribbbleApiObject) : void
2
{
3
    // Set Plugin Path

4
    $this->pluginPath = dirname(__FILE__);
5
 
6
    // Set Plugin URL

7
    $this->pluginUrl = WP_PLUGIN_URL . '/wp-Dribbble';
8
9
    add_shortcode('Dribbble', array($this, 'shortcode'));
10
11
    // Add shortcode support for widgets

12
    add_filter('widget_text', 'do_shortcode');
13
14
    $this->dribbbleApiObject = $dribbbleApiObject;
15
}

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 a similar name. Since our plugin is called WP-Dribbble, we'll call the template tag wp_Dribbble().

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

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.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.