Creating A WordPress Plugin With Composer and the Mailgun API

/ PHP / by Paul Robinson / 2 Comments
This post was published back on April 2, 2015 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

Composer is an extremely powerful tool for PHP developers and I love it, but how about when you are building a WordPress plugin?

WordPress has a lot of built in features but having access to the massive library of packages available on sites like Packagist is amazing, so the question is how do you use Composer along with WordPress?

Prerequisites

Since we are working with Composer I’m going to assume you have it installed on your local environment, whether that be a local server or a VM like Vagrant. You’ll also need a command prompt or shell open in your plugin folder (once you’ve created it).

If you don’t have Composer installed head over to the Composer website & follow the instructions. Scroll a little further down for Windows installation instructions.

If you’d like to grab a copy of the source so you can follow along, or for reference you can grab it below.

Composing A Plugin

First we are going to setup a normal WordPress plugin. Just make yourself a folder in your WordPress install’s plugins folder, I’m going to call mine login-attempt. Inside there make yourself a file for the plugin code, I’m calling mine login-attempt.php.

Now we have the plugin files created lets make it a plugin by adding in the plugin header.

If you want to follow along we are going to make a plugin that will send an email to the specified address each time a failed login attempt is detected. I guess you could say it’s a little pointless, but I guess it could have a genuine use too. We are going to use Composer to pull in the Mailgun API so we can use Mailgun to send the emails.

Require Mailgun

Now let’s pull in the Mailgun API. All you need to do is open a command prompt or terminal and navigate to your plugin folder. Then run:

Use the first if you installed Composer globally, the second if you didn’t.

Then in your plugin file add the following straight after the plugin header.

Now we can use Mailgun’s API. Awesome huh? Now we could stop there since you now know how to use Composer in your WordPress plugin, but what the hell, let’s finish things off.

Making An Options Page

First let’s make an options page. To do this we are going to use the WordPress Settings API. We are going to house all of our code in a Class. Why? Well, why not? Seriously though, it helps keep things organized at the very least.

This is a good starting point for your plugin class. We have a variable (property) to store our options which we populate in the __construct and we also run an init method. The init method will be responsible for running all of your add_action calls. This is how we are going to create our options page & hook onto the action called when a login fails. First let’s add the actions responsible for creating the options page & allowing us to use the Settings API.

Keep in mind if you try to run anything now you’ll get a nasty error, but that’s okay. If you are unfamiliar array( $this, 'function_name' ) is a way to allow WordPress to accept a function that is located inside a class. Although I can’t find anything to confirm I believe this is called Array Callable syntax.

Now let’s make our methods. Although we only call two via the actions there are a few needed as each section created via the Settings API also call a method to render their fields.

I have left spacing in to keep readability up a little, but feel free to crush things together if you like. I prefer white space and readability (in PHP at least) over the minutiae of space saved by removing the spacing though.

Basically all we are doing here is using the WordPress Settings API to create some settings fields and render out a checkbox, to enable or disable notifications; an input, to hold the Mailgun API key; an input, to hold the Mailgun domain; and an input, to hold the email to send notifications to. There is another method to add some section text, and a final one that outputs a form and outputs the fields created by the Settings API.

I won’t go through the Settings API too much as that is a tutorial in itself, however feel free to have a poke around the WordPress codex page for more information. If you are wondering how the options are saved, that is handled automatically, by WordPress thanks to the Settings API.

Sanitize Options

While WordPress does take care of most things for us with the Settings API, it doesn’t assume the data we want to allow. This means that things like HTML tags will be saved if they are entered. We don’t want that, so we are going to add a simple sanitization method to remove anything but text from our text fields. We’ll also add a special case to sanitize our email address.

First let’s tell WordPress to run our sanitization method when our settings are saved. To do this you add the method to the register_settings function from when we created our settings using the Settings API. Again we must use Array Callable syntax.

Now let’s create the sanitization method.

You can place this anywhere you like inside your class. I have mine just below the lam_settings_section_render method.

So what is happening here? Well it’s pretty simple. When WordPress calls the sanitization method it passes all the input that are attached to that register_setting call. In this case that is all of our input.

We simply loop through each item sanitizing it using WordPress’ helpful sanitize_text_field function that removes anything harmful and makes HTML safe. If we are being passed our email address we check for an empty value, if we have one then we can’t proceed as we need a valid address to send our notifications to, so we throw an error using the Settings API. Otherwise we sanitize the email using WordPress’ build in email sanitization function.

All of this is appended to a new array in the same format as the original input array, then we return the new output.

Sending The Notification

If you give your options page a try you should now be able to save data into your fields. If you try to save leaving the email address blank you should receive an error explaining you cannot have a blank email.

Now let’s create our method for sending out our failed login notification. First we need to add our action into the init method.

Nothing we haven’t see before here, so let’s move on.

This is probably the simplest part of the plugin.

Again place this wherever you’d like inside your class. I have mine directly under the init method as it is technically the meat & potatoes of the whole plugin.

The code is fairly simple. First we check for required options. So if notifications aren’t turned on, pass back to WordPress; if we don’t have an email address to send to, pass back to WordPress; and if there is no domain or key present, we pass back to WordPress.

Next we gather some data for sending out our mail. First the name of the blog and the current time. Feel free to customize the time, I am just using RFC 2822 format for simplicity. The last piece of data we need is the site name (domain) so we can create a from address. This little snippet is shamelessly pulled from WordPress’ core but it does the job.

Finally we create an instance of the Mailgun API passing the API key and then send a mail out using the sendMessage method. I’m not going to explain too much about the Mailgun API, but these are the simplest parameters available. You can see a full list on the Mailgun API website. So, for example, if you wanted to send out an HTML based email you could just change text to html.

Mission Complete

That’s it. There is another small tweak that could be made, that is to check to see if the API key & domain given are valid. If you’d like to see how I did that check out the source on github.

I’m sure there is a more efficient way to do it, feel free to share in the comments if you come up with something you like.


Composer logo, Mailgun logo, and WordPress logo used for illustrative purposes only. Copyright is held by their respective owners. Please don’t sue.

2 Comments

Author’s gravatar

How do you keep WordPress from adding auto p’s to the plugin? I have some code that I have been working on and I just found that in my widget, WordPress added a bunch of P tags around my javascript which I do want to turn into a plugin.

Reply
Author’s gravatar author

Hi Jamie,

It all depends. The function responsible for auto adding paragraphs is called wpautop. It is automatically applied to both the_content and the_excerpt. It is also automatically applied to text widgets, but only if the ‘automatically add paragraphs’ checkbox is enabled.

Can you post the code you are seeing the issue with? As far as I’m aware those are the only places wpautop is commonly used so it shouldn’t effect custom widgets.

Older Comments
Newer Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more