Create WordPress Plugins with OOP Techniques

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.

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 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.

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.

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 would call the shortcode method of the WPDribbble class.

Still Confused?

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

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 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.

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’ 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

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’ built-in functions, because they are under the class namespace.

  • $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 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.

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

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-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.

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.

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].

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.

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

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.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Muhammad Haris

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.

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 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.

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.

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 would call the shortcode method of the WPDribbble class.

Still Confused?

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

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 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.

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' 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

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' built-in functions, because they are under the class namespace.

  • $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 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.

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

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-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.

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.

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].

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.

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

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.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Muhammad Haris


Print Share Comment Cite Upload Translate Updates
APA

Muhammad Haris | Sciencx (2014-01-20T02:20:53+00:00) Create WordPress Plugins with OOP Techniques. Retrieved from https://www.scien.cx/2014/01/20/create-wordpress-plugins-with-oop-techniques/

MLA
" » Create WordPress Plugins with OOP Techniques." Muhammad Haris | Sciencx - Monday January 20, 2014, https://www.scien.cx/2014/01/20/create-wordpress-plugins-with-oop-techniques/
HARVARD
Muhammad Haris | Sciencx Monday January 20, 2014 » Create WordPress Plugins with OOP Techniques., viewed ,<https://www.scien.cx/2014/01/20/create-wordpress-plugins-with-oop-techniques/>
VANCOUVER
Muhammad Haris | Sciencx - » Create WordPress Plugins with OOP Techniques. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2014/01/20/create-wordpress-plugins-with-oop-techniques/
CHICAGO
" » Create WordPress Plugins with OOP Techniques." Muhammad Haris | Sciencx - Accessed . https://www.scien.cx/2014/01/20/create-wordpress-plugins-with-oop-techniques/
IEEE
" » Create WordPress Plugins with OOP Techniques." Muhammad Haris | Sciencx [Online]. Available: https://www.scien.cx/2014/01/20/create-wordpress-plugins-with-oop-techniques/. [Accessed: ]
rf:citation
» Create WordPress Plugins with OOP Techniques | Muhammad Haris | Sciencx | https://www.scien.cx/2014/01/20/create-wordpress-plugins-with-oop-techniques/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.