how to build a quick ‘n’ dirty WordPress plugin

Plug it in by Abekamal on deviantART

Let’s say that you’ve in the process of writing a new e-book and you want to give the opportunity to your blog readers to submit their details in a form so they can receive a notification when the e-book is ready. You need a plugin. Ok, there are a few mailing list plugins out there that you can use quickly, but the point of this article is to show you how you can build such a plugin from scratch so you can modify it in any way you want, etc. You get the idea, so let’s start.

Have a look at the demo page (opens in a new tab). You can also [download id=”9″ format=”1″].

First, make a new .php file, naming it whatever you want. I named mine “quickndirty.php” (like the one you downloaded). The first lines (the comments) are just for informative reasons (the info displayed in the “Plugins” section of your WordPress administration panel):

/*
Plugin Name: Quick'n'Dirty
Plugin URI: http://burnmind.com/howto/
how-to-build-a-quick-n-dirty-wordpress-plugin
Version: v1.00
Author: <a href="http://burnmind.com/">
burnmind.com</a>
Description: A Quick'n'Dirty WordPress plugin
 */

The whole plugin consists of one class, named “Qnd” (Quick’n’dirty). All the functions (unless stated so) are going to be included in this class. We declare 2 private variables, one to hold the database table name (make sure to use a unique name to avoid any conflicts with other tables) and one to hold an instance of wpdb:

if (!class_exists("qnd"))
{
    class Qnd
    {
        private $wpdb;
        private $qndTable;

        public function __construct ()
        {
            global $wpdb;
            $this->wpdb = $wpdb;
            $this->qndTable = $wpdb->prefix . "qnd";
        }
    }
}

The first function we are going to create is the one that will be executed when the plugin is activated and it’s going to be responsible to create the table into the database. The table is going to be created only if it is not present and it will not be deleted when the plugin is deactivated. The table consists of 4 (self-explanatory) fields:

function createTable()
{
    if($this->wpdb->get_var("show tables like '$this->qndTable'") != $this->qndTable)
    {
        $create =   "CREATE TABLE " . $this->qndTable . " (
                    id int(20) NOT NULL AUTO_INCREMENT,
                    name varchar(300) NOT NULL,
                    email varchar(300) NOT NULL,
                    location varchar(300) NOT NULL,
                    PRIMARY KEY (id)
                    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1; ";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($create);
    }
}

Next is the controller function. It’s functionality is quite straightforward: If a POST request have been made try to insert the details into the database and if not, display the form:

function controler()
{
    if (isset($_POST['nameField']))
    {
        return $this->submitDetails();
    }
    else
    {
        return $this->displayForm(false);
    }
}

We’ll first explore the displayForm function. It’s really just a simple form. The $error variable is used to check if there is an error and if there is to display a message.

function displayForm($error)
{
?>
<p>Please complete the form to send you the e-book when it's published.</p>

<?php if ($error) { ?>
<p style="color:#FF0000;"><strong>Please complete all the required fields!</strong></p>
<?php } ?>

<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<ul>
   <li>
      <label>Name:</label><br /> <input type="text" name="nameField" value="<?php echo $_POST['nameField'] ?>" /> (required)
   </li>
   <li>
      <label>E-mail:</label><br /> <input type="text" name="emailField" value="<?php echo $_POST['emailField'] ?>" /> (required)
   </li>
   <li>
      <label>Location:</label><br /> <input type="text" name="locationField" value="<?php echo $_POST['locationField'] ?>" />
   </li>
</ul>
<input type="submit" value="Submit" onclick="return validate()" />
</form>
<?php
}

submitDetails is the last function of Qnd class. First, it escapes the user’s input to prevent SQL injection. Then it checks if either the name or the e-mail fields are blank. If any of them is, it displays the form with an error message. Please note that in a proper implementation it’s recommended to use better error reporting, to check if the e-mail is valid, etc. Finally, if the required fields are there, it inserts the data into the database and displays a success message instead of the form.

function submitDetails()
{
    $name = $this->wpdb->escape($_POST['nameField']);
    $email = $this->wpdb->escape($_POST['emailField']);
    $location = $this->wpdb->escape($_POST['locationField']);
			
    if($name=='' || $email=='')
    {
        $this->insertForm(true);
    }
    else
    {
        $insert = "INSERT INTO $this->qndTable
                  (name, email, location)
                  VALUES ('$name', '$email', '$location')";

        $this->wpdb->query($insert);
        echo 'Your details have been submitted. Thank you!';
    }
}

The plugin is almost ready. Place the following code outside of the Qnd class and you’re ready. The code creates an instance of the Qnd class, registers the shortcode “QUICKNDIRTY” to be used to call the plugin and sets the function createTable to be executed every time the plugin is activated from the WordPress administration panel.

if (class_exists("qnd"))
{
    $qnd = new Qnd();
}

if (isset($qnd))
{
    add_shortcode('QUICKNDIRTY', array( &$qnd, 'controler'));
    register_activation_hook(__FILE__, array(&$qnd, 'createTable'));
}

To use the plugin, place the .php file into your plugins folder, activate it in the administration panel, create (or edit) a post/page and insert the shortcode QUICKNDIRTY in brackets ([]).

Have a look at the demo page (opens in a new tab). You can also [download id=”9″ format=”1″].

Photo by ~abekamal