WordPress Plugin Construction for the Non Programmer: Part VII

WordPress Plugin Construction for the Non Programmer: Part VII

Welcome to the seventh post in my series on building a WordPress plugin from scratch. This tutorial series requires no programming experience, but I do suggest you start from the first post in this series if you’re a total newbie to WordPress development. Just a couple things to keep in mind about this series if you’re just tuning in:

Five Official “Cover my Butt” Statements

  • At the time of this writing, the most up to date WordPress version is 3.4.1. It might be different by the time you read this.
  • I’m assuming you already know how to install a basic WordPress site, if you’re unsure please see their www.wordpress.org.
  • Please do NOT attempt anything in these tutorials on one of your live WordPress sites. Rather, set up a subdomain and a brand new WordPress installation to use for plugin testing purposes only.
  • If you’re confused by any of the code or terminology above, please go back and read the first six posts in this series. I’ve posted links at the close of this post.

Plugin Source Code for This Tutorial

Below is the source code for this tutorial. I’ve provided this for example purposes but strongly encourage you to recode this yourself from scratch and to experiment with some minor modifications. You’ll also notice that this plugin is slightly different than the one we’ve been working on in this series.

This plugin, which we’ll be developing over the next several posts in this series, will allow you to add an affiliate promotion in your WordPress dashboard which and have it show up below every blog on your WordPress site:

{code type=php}

<?php

/*/

Plugin Name: SJC Affiliate Promotions

Plugin URI: www.penetrationmedia.com

Description: Simple plugin for adding and managing affiliate promotions on your WordPress posts.

Version: 101

Author: Seth Czerepak

Author URI:  www.sethczerepak.com

/*/

// check for existing class

if(!class_exists(‘SJC_AffiliatePromos’)) {

// create class

class SJC_AffiliatePromos {

//create function for creating table in WP DB

function SJC_AffiliatePromos_CreateTable () {

global $wpdb;

//define table name

$table_name = $wpdb->prefix . ‘sjc_affiliate_promotions’;

//create code for constructing table

$sql = “CREATE TABLE $table_name (

id int(100) NOT NULL AUTO_INCREMENT,

date_created datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

date_updated datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

promotion_name VARCHAR(200) NOT NULL,

promotion_body text NOT NULL,

promotion_link VARCHAR(200) DEFAULT ” NOT NULL,

UNIQUE KEY id (id)

);”;

//include WP files essential for creating your own tables

require_once(ABSPATH . ‘wp-admin/includes/upgrade.php’);

dbDelta($sql);

}

//function for adding dummy data to your new table

function SJC_AffiliatePromos_DummyData() {

global $wpdb;

//define table name

$table_name = $wpdb->prefix . ‘sjc_affiliate_promotions’;

//set dummy data variables

$promotion_name = ‘Newsletter Signup’;

$promotion_body = ‘For more cool free information sign up for our newsletter. Just fill in the form on the upper right hand corner of this website!’;

$rows_affected = $wpdb->insert($table_name, array(‘date_created’ => current_time(‘mysql’), ‘promotion_name’ => $promotion_name, ‘promotion_body’ => $promotion_body));

}

function ActivePromotion($full_content = ”) {

global $wpdb;

//grab promotions data

$promotion_data = $wpdb->get_row(“SELECT * FROM wp_sjc_affiliate_promotions WHERE id = ‘1’”, ARRAY_A);

//prepare to display promotion in blog footer

$affiliate_promotion = $promotion_data[‘promotion_body’];

$full_content .= $affiliate_promotion;

return $full_content;

}

//create admin page

function SJC_AffiliatePromos_AdminPage() {

//lock out unauthorized users

if (!current_user_can(‘manage_options’)) {

wp_die( __( ‘KEEP OUT! Authorized Personnel Only!’ ) );

}//end lock out

//spit out html for admin area

echo ‘<div>’;

echo ‘<h1>Welcome to Affiliate Promotions!</h1>’;

echo ‘<p>This will be the command center for the Affiliate Promotions Plugin.</p>’;

echo ‘</div>’;

//grab users information from the database

global $wpdb;

//grab promotions data

$promotion_data = $wpdb->get_row(“SELECT * FROM wp_sjc_affiliate_promotions WHERE id = ‘1’”, ARRAY_A);

echo ‘Active Affiliate Promotion:’;

echo $promotion_data[‘promotion_name’];

echo “<br />”;

echo $promotion_data[‘promotion_body’];

} //end of html for admin page

function SJC_AffiliatePromos_Handler_PluginMenu() {

add_options_page(‘SJC Affiliate Promotions’, ‘SJC Affiliate Promotions’, ‘manage_options’, ‘sjc-affiliate-promotions-admin’, array(&$this,SJC_AffiliatePromos_AdminPage));

}//end plugin menu

} // close class

} //close check or existing class

//if the class exists, assign a handler to it

if(class_exists(SJC_AffiliatePromos)){

$SJC_AffiliatePromos_Handler = new SJC_AffiliatePromos();

//run code to create table when plugin is activated

register_activation_hook(__FILE__,array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_CreateTable’));

//run code to populate table with dummy data when plugin is activated

register_activation_hook(__FILE__,array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_DummyData’));

//tell your handler to build the plugin menu using WP action

add_action(‘admin_menu’, array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_Handler_PluginMenu’),1);

//add active promotion to your blog footers

add_filter(‘the_content’, array($SJC_AffiliatePromos_Handler, ‘ActivePromotion’));

}//close assignment of handler

{/code}

Breakdown of the SJC Affiliate Promotions Source Code

For the sake of instruction, I’m going to break down the source code one section at a time. I’ll be summarizing the coding techniques already discussed within this post series as well as explaining the sections of code which contain new techniques. Let’s start with the first block of code, the plugin description:

{code type=php}

<?php

/*/

Plugin Name: SJC Affiliate Promotions

Plugin URI: www.penetrationmedia.com

Description: Simple plugin for adding and managing affiliate promotions on your WordPress posts.

Version: 101

Author: Seth Czerepak

Author URI:  www.sethczerepak.com

/*/

{/code}

This code contains the plugin description, which we covered in detail in the first post of this series “How to Create Your Very First WordPress Plugin.” In the next section of code, we check to see if a class with our unique class name already exists. If it doesn’t, we create the unique class for our plugin:

{code type=php}

// check for existing class

if(!class_exists(‘SJC_AffiliatePromos’)) {

// create class

class SJC_AffiliatePromos {

{/code}

The techniques used in the code above were covered in the second post of this series. Next, we get into the code which contains the first step for this tutorial…creating a table for your plugin within the WordPress database:

Step #1: Create Your WordPress Database Table

{code type=php}

//create function for creating table in WP DB

function SJC_AffiliatePromos_CreateTable () {

global $wpdb;

//define table name

$table_name = $wpdb->prefix . ‘sjc_affiliate_promotions’;

//create code for constructing table

$sql = “CREATE TABLE $table_name (

id int(100) NOT NULL AUTO_INCREMENT,

date_created datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

date_updated datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

promotion_name VARCHAR(200) NOT NULL,

promotion_body text NOT NULL,

promotion_link VARCHAR(200) DEFAULT ” NOT NULL,

UNIQUE KEY id (id)

);”;

//include WP files essential for creating your own tables

require_once(ABSPATH . ‘wp-admin/includes/upgrade.php’);

dbDelta($sql);

}

{/code}

In the code above, we start with the “method” (aka “function,” as I explain in part three of this series), which we will use to create the database structure:

{code type=php}

function SJC_AffiliatePromos_CreateTable () {

{/code}

We begin this function with the global “$wpdb” which we covered in part five of this series:

{code type=php}

global $wpdb;

{/code}

After that, you’ll see a line of code which establishes a name for our database table:

{code type=php}

//define table name

$table_name = $wpdb->prefix . ‘sjc_affiliate_promotions’;

{/code}

This code ^ uses some new techniques. First, we have the variable “prefix,” which as you can see is part of the “$wpdb” class. This variable stores the standard prefix “wp_” which is used in all existing WordPress database tables.

Next, you use the period (.) character to “concatenate” (concatenation is explained in part six of this series) the “wp_” prefix to your very own table name. The table name will be “sjc_affiliate_promotions.” So the end result will be a variable named “$table_name” which represents the exact table name of “wp_sjc_affiliate_promotions.”

The “sjc” in this example represents my full initials. I’ve done this to ensure that my table is unique. If I’d not done this, someone could have also named their table “affiliate_promotions” and we’d have a table naming conflict on our hands. I suggest you use your own “signature” to do the same when creating your WordPress database tables.

After this code, you’ll find a considerably complicated block of code for creating the actual structure of your database table:

{code type=php}

$table_name = $wpdb->prefix . ‘sjc_affiliate_promotions’;

//create code for constructing table

$sql = “CREATE TABLE $table_name (

id int(100) NOT NULL AUTO_INCREMENT,

date_created datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

date_updated datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

promotion_name VARCHAR(200) NOT NULL,

promotion_body text NOT NULL,

promotion_link VARCHAR(200) DEFAULT ” NOT NULL,

UNIQUE KEY id (id)

);”;

{/code}

In the fifth post of this series, I described how WordPress database tables are structured, in columns and rows like an Excel spreadsheet. The code which comes after the “$sql=” represents the columns which will be created in your database. Notice that we use a command called “CREATE TABLE” to create a table with the “$table_name” which you assigned earlier (“wp_sjc_affiliate_promotions”).

Next, you see seven lines of code. The first six of these tell WordPress what kind of database columns to create. We’ll talk about the seventh line in just a moment. To keep this explanation simple, I’m going to translate each of the first six lines and show you exactly what they’re doing:

  • id int(100) NOT NULL AUTO_INCREMENT

Here, a column named “id” is being created. This column will contain numbers/integers (“int” means “integer”) and the maximum value of these integers will be 100. This means that the “id” column will only be able to store 100 records (rows are called “records) of data. The numbers in this column will count upwards one at a time (AUTO_INCREMENT) automatically as new rows of data are stored.

  • date_created datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

Here, a column named “date_created” is being created. This column will contain a date/time stamp (“datetime”) and the DEFAULT value will be ‘0000-00-00 00:00:00’ instead of just a null value (NOT NULL).This will help us keep track of the exact time when records are first stored in the “wp_sjc_affiliate_promotions” table.

  • date_updated datetime DEFAULT ‘0000-00-00 00:00:00’ NOT NULL,

Here a column named is “date_updated” is being created. This column will also contain a date/time stamp (“datetime”) and the DEFAULT value will be ‘0000-00-00 00:00:00’ instead of just a null value (NOT NULL).This will help us keep track of the exact time when records in the  “wp_sjc_affiliate_promotions” table are updated.

  • promotion_name VARCHAR(200) NOT NULL,

Here, a column named “promotion_name” is being created. This column will contain the name of your affiliate promotions, which will contain a VARiety of CHARacters, both numbers and letters. The data in this column must be kept under (200) characters and the column must contain data (NOT NULL).

  • promotion_body text NOT NULL,

Here, a column named  “promotion_body” is being created. This column will contain the description of your affiliate promotions, the “text” data type can contain an unlimited amount of characters and the column must contain data (NOT NULL).

  • promotion_link VARCHAR(200) DEFAULT ” NOT NULL,

Here, a column named “promotion_link” is being created. This column will contain the link to your affiliate promotions, which will contain a VARiety of CHARacters, both numbers and letters as well as special characters (/, < or > for the hyperlink). The data in this column must be kept under (200) characters and the column must contain data (NOT NULL).

All of these commands create columns and are followed by a comma. However, the final line of the MY SQL command for creating the table does something different:

  • UNIQUE KEY id (id)

This command is setting the “id” column as a “UNIQUE KEY.” There can only be one unique key per table and the unique key is used to store each record as a unique value. This makes it possible to sort through and to retrieve specific data from your WordPress database.

Finally, we have two lines of code which WordPress requires in order to create tables in the WordPress database:

{code type=php}

//include WP files essential for creating your own tables

require_once(ABSPATH . ‘wp-admin/includes/upgrade.php’);

dbDelta($sql);

}

{/code}

The “require_once” function means that the file between “(“ and “)” is required in order to run the current script. That “ABSPATH” is another PHP global which generates the URL of the host site. So if your WordPress site were sitting on a domain called “http://example.com,” this code…

{code type=php}

ABSPATH . ‘wp-admin/includes/upgrade.php’;

{/code}

…would translate into:

http://example.com/’wp-admin/includes/upgrade.php

After the “require_once” function, the “dbDelta” function executes the actual table creation. Remember that the variable “$sql” stores the commands for our database structure. I won’t go into detail about how the “’wp-admin/includes/upgrade.php” or the “dbDelta” work because it’s not knowledge which is required for creating your WordPress database tables.  Just be sure you use them when creating tables and you’ll be fine.

Our next block of code contains a function which creates and inserts “dummy data” into your new database table so that you can test the creation of your table…

Step #2: Add Test Data to Your WordPress Database Table

{code type=php}

//function for adding dummy data to your new table

function SJC_AffiliatePromos_DummyData() {

global $wpdb;

//define table name

$table_name = $wpdb->prefix . ‘sjc_affiliate_promotions’;

//set dummy data variables

$promotion_name = ‘Newsletter Signup’;

$promotion_body = ‘For more cool free information sign up for our newsletter. Just fill in the form on the upper right hand corner of this website!’;

$rows_affected = $wpdb->insert($table_name, array(‘date_created’ => current_time(‘mysql’), ‘promotion_name’ => $promotion_name, ‘promotion_body’ => $promotion_body));

}

{/code}

We’ve already covered most of the above techniques in the fifth and sixth tutorials of this series. However, the following line of code contains a new technique:

{code type=php}

$rows_affected = $wpdb->insert($table_name, array(‘date_created’ => current_time(‘mysql’), ‘promotion_name’ => $promotion_name, ‘promotion_body’ => $promotion_body));

}

{/code}

The “$rows_affected” variable is storing a series of commands which use the “$wpdb” class once again. This time we’re using it to “insert” the data between “(“ and “)” into the WordPress database. The “insert” function takes two arguments, which are separated by a comma. The first argument ($table_name) is the name of the table where the data will be inserted.

The second argument is an array of data which contains the table columns, followed by the data which is to be inserted into those columns:

{code type=php}

array(‘date_created’ => current_time(‘mysql’), ‘promotion_name’ => $promotion_name, ‘promotion_body’ => $promotion_body)

{/code}

The following is a breakdown of what this code ^ is doing:

  • The “current_time(‘mysql’)” function inserts the current time into the “date_created” column.
  • The “$promotion_name” variable is inserted into the “promotion_name” column which we created.
  • The “$promotion_body” variable is inserted into the “promotion_body” column which we created.

This concludes the methods within your plugin class which create the table and which insert the dummy data into it. Next, we have method which adds your affiliate promotion to the bottom of each blog post:

{code type=php}

function ActivePromotion($full_content = ”) {

global $wpdb;

//grab promotions data

$promotion_data = $wpdb->get_row(“SELECT * FROM wp_sjc_affiliate_promotions WHERE id = ‘1’”, ARRAY_A);

//prepare to display promotion in blog footer

$affiliate_promotion = $promotion_data[‘promotion_body’];

$full_content .= $affiliate_promotion;

return $full_content;

}

{/code}

The above techniques are covered in the first tutorial of this series. The only difference is the “.=” which adds the “$affiliate_promotion” variable to the end of your post content. Next, we use the techniques discussed in the third and fourth tutorials to create our admin menu and admin page and to display your affiliate promotions data in the admin area:

{code type=php}

//create admin page

function SJC_AffiliatePromos_AdminPage() {

//lock out unauthorized users

if (!current_user_can(‘manage_options’)) {

wp_die( __( ‘KEEP OUT! Authorized Personnel Only!’ ) );

}//end lock out

//spit out html for admin area

echo ‘<div>’;

echo ‘<h1>Welcome to Affiliate Promotions!</h1>’;

echo ‘<p>This will be the command center for the Affiliate Promotions Plugin.</p>’;

echo ‘</div>’;

//grab users information from the database

global $wpdb;

//grab promotions data

$promotion_data = $wpdb->get_row(“SELECT * FROM wp_sjc_affiliate_promotions WHERE id = ‘1’”, ARRAY_A);

echo ‘Active Affiliate Promotion:’;

echo $promotion_data[‘promotion_name’];

echo “<br />”;

echo $promotion_data[‘promotion_body’];

} //end of html for admin page

function SJC_AffiliatePromos_Handler_PluginMenu() {

add_options_page(‘SJC Affiliate Promotions’, ‘SJC Affiliate Promotions’, ‘manage_options’, ‘sjc-affiliate-promotions-admin’, array(&$this,SJC_AffiliatePromos_AdminPage));

}//end plugin menu

} // close class

{/code}

} //close check or existing class

After closing our plugin class, we assign a handler to our class (explained in the second tutorial of this series):

{code type=php}

//if the class exists, assign a handler to it

if(class_exists(SJC_AffiliatePromos)){

$SJC_AffiliatePromos_Handler = new SJC_AffiliatePromos();

{/code}

Finally, we use some new WordPress functions to execute the new methods we’ve added to our class…

Step #3: Have Your Plugin Class Handler Create Your Table and Add Your Data

In the code below, we use the WordPress function “register_activation_hook” to execute some commands when your plugin is activated:

{code type=php}

//run code to create table when plugin is activated

register_activation_hook(__FILE__,array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_CreateTable’));

//run code to populate table with dummy data when plugin is activated

register_activation_hook(__FILE__,array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_DummyData’));

{/code}

The “register_activation_hook” takes two arguments, which are separated by a comma. The first argument is the name of the file which, when activated, initiates the function given in the second argument.

That “_FILE_” that you see in both uses of the “register_activation_hook” represents the current file, which is your actual plugin file. So applying what you learned in the past tutorials of this series, this line of code….

{code type=php}

//run code to create table when plugin is activated

register_activation_hook(__FILE__,array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_CreateTable’));

{/code}

…would translate into this command:

“WordPress! When the current plugin file is activated, I want you to use the ‘$SJC_AffiliatePromos_CreateTable’ method to create a new table in the WordPress database.”

And this line of code…

{code type=php}

//run code to populate table with dummy data when plugin is activated

register_activation_hook(__FILE__,array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_DummyData’));

{/code}

…would translate into this command:

“WordPress! When the current plugin file is activated, I want you to use the ‘$SJC_AffiliatePromos_DummyDate’ method to put some dummy data into the new WordPress database table.”

Once that’s done, we apply the techniques covered in the first three tutorials in this series to set up our plugin’s admin page AND to add our affiliate promotions data to the end of our blog posts:

{code type=php}

//tell your handler to build the plugin menu using WP action

add_action(‘admin_menu’, array($SJC_AffiliatePromos_Handler, ‘SJC_AffiliatePromos_Handler_PluginMenu’),1);

//add active promotion to your blog footers

add_filter(‘the_content’, array($SJC_AffiliatePromos_Handler, ‘ActivePromotion’));

}//close assignment of handler

{/code}

And that’s all there is to the source code for this tutorial…but there’s more!

What’s Next?

Okay, so now you know how to create a WordPress plugin, alter post and title data, add an admin menu and admin page, create a new database table, populate it with data AND grab data out of the WordPress database to display on your WordPress site and in the admin area!

But if you think this is exciting, wait till you see what we’re doing next. We’ll be creating some forms in the admin area so you can make store and update information in your WordPress database.

More to come!

-Best,

Seth C

Other Posts in This WordPress Plugin Construction Series

How to Create Your Very First WordPress Plugin
WordPress Plugin Construction for the Non-Programmer: Part II
WordPress Plugin Construction for the Non-Programmer: Part III
WordPress Plugin Construction for the Non-Programmer: Part IV
WordPress Plugin Construction for the Non-Programmer: Part V

WordPress Plugin Construction for the Non-Programmer: Part VI