how to build a quick ‘n’ dirty WordPress plugin

Plug it in by Abekamal on deviantART
Photo 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 the tutorial’s source code.

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://www.burnmind.com/howto/how-to-build-a-quick-n-dirty-wordpress-plugin
Version: v1.00
Author: <a href="http://www.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 the tutorial’s source code.

 

how to feed jQuery UI’s Autocomplete with a database-generated dataset

Dirty Smile by Aukon on deviantART
Photo by ~Aukon on deviantART

Recently, I had to use jQuery UI’s Autocomplete widget. Its use is straightforward when you have a static datasource. When the datasource is larger though (from a few thousand to several million records) and you need to feed the Autocomplete widget with a remote dataset (provided in the example by a php script which queries a database) this are becoming a bit more complex because the documentation is a little vague on the matter and it lacks of a proper example.

Have a look at the demo page (opens in a new tab). You can also download the tutorial’s source code.

We’re going to use a text field with the id “auto”:

<input type="text" id="auto" />

The JavaScript code is quite straightforward. Inside the document.ready function, we bind the Autocomplete widget to the text field with the id “auto”. As a source for the Autocomplete widget we specify the php script “search.php”. We also set the minimum length of characters (3) that the Autocomplete widget needs before it activates itself.

$(document).ready(function()
{
    $('#auto').autocomplete(
    {
        source: "search.php",
        minLength: 3
    });
});

The php script is where all the magic happens. The most important piece of information is that the Autocomplete widget sends the content of the text field to the php script via the GET method in a variable called “term”.

$mysqli = new mysqli('localhost', 'yourUserName', 'yourPassWord', 'yourDatabase');
$text = $mysqli->real_escape_string($_GET['term']);

$query = "SELECT name FROM bands WHERE name LIKE '%$text%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
    if (!$first) { $json .=  ','; } else { $first = false; }
    $json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;

The above script will connect to the database, perform a query based on the term written by the user in the text field and will echo the results (to be used by the Autocomplete widget) in the following JSON format: [{"value":"Nirvana"},{"value":"Pink Floyd"}].

If you haven’t done it already, have a look at the demo page (opens in a new tab). You can also download the tutorial’s source code.

 

hello in all languages WordPress plugin

Hello in all languages

Hello! A couple of months ago I was in need of a script that figures out the location of the visitors of a website (using their IP) and displays a “hello” in their own language. After building this script I wrapped it up as a WordPress plugin under the name “hello in all languages”.

Hello in all languages is a free WordPress plugin that displays a “hello” word translated to the official language of the country the visitor’s IP belongs to. You can find more information on its official page and you can download it from WordPress Plugin Directory.

If you try it, I would be happy to receive your feedback. I hope you enjoy it!