Writing A WordPress Plugin : 05 Deleting and Activating

At this point, we have a semi-functioning WordPress plugin that could do something if we created a “customer” storefront. But without being able to update (activate and deactivate games) or delete them, this thing would be very limited in its functionality. Let’s move forward and be able to make some changes to our plugin.

As noted before, we will not be covering the general aspects of how to write PHP code or work with MySQL. To learn MySQL, you can get tutorials online and in printed form. To learn PHP, you can find resources online and in printed form here. Great free tools to use to write code (known as “Integrated Development Environments” or IDEs) are Komodo (for OS X) and NetBeans (for Windows).

Deleting and Activating The Data

Difficulty: Easy
Completion Time: 1-2 hour
What We Will Be Using: PHP, WordPress Platform, MySQL

Creating The Links To Activating Games
Yesterday, we looked at using the POST method for adding a game to the library which is perfect for using that form, but the GET method is going to what we use to activate/deactivate games and delete them. Let’s look at the code to build a link to activate or deactivate a game.

if($game_status == 0 || $game_status == 1){ // Status of the game is currently pending or inactive
echo "activate";
if($game_status == 2){ // Status of the game is currently active

There are three things to note in this logic: we use the status of the game to decide if we need to activate or deactivate the game, we are using the “action=activate” to define what information the page will be receiving, and the game_id which will define which game we are activating or deactivating. These links will be posted and in the games_options() when we display all the games, giving the administrator full control over what the user experiences.

Updating The Database
To actually update the database, we will need to collect the information from the URL by posting the following code before you display the data, outside of the foreach loop and update the database:

if($_GET["action"] == "activate"){
$sql = "UPDATE " . $table_name . " SET `status` = 2 WHERE id = " . $_GET["id"];
$results = $wpdb->query($sql);
echo "

Game Activated.

if($_GET[“action”] == “deactivate”){
$sql = “UPDATE ” . $table_name . ” SET `status` = 0 WHERE id = ” . $_GET[“id”];
$results = $wpdb->query($sql);
echo ”

Game Deactivated.


This IF statement is situational and simply updates the status of the game depending on what the action needs.

Implementing The Delete Function
The delete action is very similar to the activate/deactivate action, except there is no IF statement. Here is the link to delete a game, it should be placed right after the activate/deactivate link:

echo " - delete


Note that we did not close the cell in the activate/deactivate IF statement because this includes the delete link afterwards. Now for receiving the code:

if($_GET["action"] == "delete"){
$sql = "DELETE FROM " . $table_name . " WHERE id = " . $_GET["id"];
$results = $wpdb->query($sql);
echo "

Game Deleted.


Super simple code that goes after the activate/deactivate retrieving code. And that is it! We are one more step closer to a complete plugin. A few more steps and we will have a fully functioning administration side for our plugin.

Writing A WordPress Plugin : 04 Inserting Data

So far with this plugin, we have a game plan for what this plugin is supposed to do, established a place in the WordPress administration environment, and have begun pulling data and formatting the information. But a plugin without an ability to insert new data is worthless, so lets add this feature.

As noted before, we will not be covering the general aspects of how to write PHP code or work with MySQL. To learn MySQL, you can get tutorials online and in printed form. To learn PHP, you can find resources online and in printed form here. Great free tools to use to write code (known as “Integrated Development Environments” or IDEs) are Komodo (for OS X) and NetBeans (for Windows).

Inserting The Data

Difficulty: Intermediate
Completion Time: 1-2 hour
What We Will Be Using: PHP, WordPress Platform, MySQL

Creating The Form
To insert the data, we need to create the form. WordPress suggests that we create a completely separate file, so let’s create a file called add_game.php which will contain ONLY our form. Within this file, we will insert the following code:

function add_game() {

// Add Section
echo "

" . __( 'Add A Game To The Library', 'mt_trans_domain' ) . "


// Insert form elements here


There are three things to note in this form. First, we put the form within a function called add_slide(). This will allow us to put this form in its own page on the WordPress administration menu in the Game Plugin section (we will come back to this in a minute). Secondly, the form uses the method POST, which we will discuss at the end of this post. Finally, we added the hidden field action with the value add so that when we go to collect the information, we will be able to distinguish what to do with this information. Now, once you have inserted your form elements, we are ready to add it to the plugin section. Open up game_plugin.php and add this line of code at the very top of the file:


Also note in the last post that we had created a menu for this plugin. In that code, you will find this line:

add_submenu_page( 'games', 'Add Game', 'Add Games', 'administrator', 'add_game', 'add_game' );

The add_game is the name of our function that has the form and this piece of code allows us to go to that form in the administration menu any time to add a game. Next, we will get the information from that form we just created.

Collecting the Data
Now we will be collecting the data from the form and inserting it into the database. Go ahead and add this code within the games_option() function:

if( $_POST[ 'action' ] == 'add' ) { // MySQL : Add Game
global $wpdb;
$table_name = $wpdb->prefix . "games";

$insert = "INSERT INTO " . $table_name .
" (title, text) " .
"VALUES ('". $_POST[ 'title' ] . "','" . $_POST[ 'text' ] . "')";
$results = $wpdb->query( $insert );

// Put an options updated message on the screen
echo "

Game Added.


We look for the action with the value add and then collect the data passed to this file and insert it into the database. There are more tricks that you can do with the data and results from adding the information into the database, but this code will work for you.

Why POST Method?
One great question that I received about this code is why I used the POST method in the form here, but later we will see that I use the GET method. There are two important things about this: it keeps the URL short and it keeps the data private. While the privacy aspect of this feature is not as important with adding games, the length of a URL is extremely important. If someone were to add a game with an extremely long description, the address could end up being pages long. With the POST method, the data is still transferred, but the URL remains the same regardless of what is going communicated. Later, we will be using the GET method for deleting games and deactivating them. The primary reason for this is because it is easy to build a link with the data already in it. (More on this in a future post)

Writing A WordPress Plugin : 03 Displaying Data

The last two days we have simply been doing the underlying planning for this project and creating the database for this plugin, but now it is time to get into the coding and the entire WordPress Codex. In today’s post, we will be creating the initial file and ensuring that we are displaying the information in the database correctly.

As noted before, we will not be covering the general aspects of how to write PHP code or work with MySQL. To learn MySQL, you can get tutorials online and in printed form. To learn PHP, you can find resources online and in printed form here. Great free tools to use to write code (known as “Integrated Development Environments” or IDEs) are Komodo (for OS X) and NetBeans (for Windows).

Displaying The Data

Difficulty: Easy
Completion Time: 1-2 hour
What We Will Be Using: PHP, WordPress Platform, MySQL

Creating the Main Plugin File
Before we get into coding, we need to create our main plugin file with a unique PHP filename in a folder that will be the name of our plugin. For our project, we named the file game_plugin.php and the folder it goes into wp_game_plugin. You can really name it whatever you want, it doesn’t make any difference, but make sure that it is memorable and appropriate to your project. Open your blank main file and at the top, put this header information with your own data:

Plugin Name: Game Plugin
Plugin URI: http://www.78p.tv
Description: A plugin to create, display, edit, and remove a game.
Version: 0.1
Author: Jeremy Smith
Author URI: http://www.78p.tv

// Copyright 2011 seventy8productions

Now upload this whole folder to “../location/of/your/wordpress/wp-content/plugins“, open your WordPress administration panel in your browser, navigate to the Plugins sections, and you should see your plugin in the list.

Getting the Data From The Database
Now we will get data from the database. Before we do this, open up your MySQL database manager and manually add some correct information that you might see in the database that we can then pull from it. Once you have done this, open up your main plugin file again.

We will be putting in code to give our plugin a spot on the left side administration menu of WordPress. To understand what this means, you can look up the details of the different files for add_action, add_menu_page, and add_submenu_page to get deeper details of each. Add the following code and change the names to what you want (make sure you change it exactly the same everywhere):

add_action('admin_menu', 'games', 10, 2 );

function games() {
add_menu_page('Games LIst', 'Games List', 'administrator', 'games', 'games_options');

add_submenu_page( 'games', 'Games List', 'Games List', 'administrator', 'games', 'games_options');
add_submenu_page( 'games', 'Add Game', 'Add Games', 'administrator', 'add_game', 'add_game' );

function games_options() {

Re-upload this file to the plugins folder on your server, log in to WordPress and look for your plugin in the Administration Menu.

Formatting Your Data Correctly
Now that our page is displaying in the administration page, lets go ahead and grab some information. You can get a more detailed list of $wpdb if you feel lost. In your main plugin file, add the following code into your games_options function:

global $wpdb;
$table_name = $wpdb->prefix . "games"; // Change the quotations to what your MySQL database name is

$myrows = $wpdb->get_results( "SELECT * FROM " . $table_name );

foreach ($myrows as $myrows) {
echo $myrows->id . ", " . $myrows->title . ", " . $myrows->description . ", " . $myrows->materials . ", " . $myrows->status;
// Change these items to the columns in your database

It is that easy! You now have some information pulled from your database and coming up in your plugin in WordPress that can be accessed via a custom slot in the Administration Menu.

Writing A WordPress Plugin : 02 Defining MySQL

Yesterday we talked about the first step in writing a plugin, to have a solid plan written out before ever starting to write code. The next step in the process of effectively writing a plugin is to thoroughly map out and create the database we will be using to host the data we collect with this plugin. WordPress natively uses MySQL, the most dominate open-source database and integrates extremely well with PHP. While we will be discussing the strategy and process for establishing this MySQL database, we will not be getting into the step-by-step process of making the database or how to manually insert data into it. There is already an exhaustive list out there on how to do so, both online and in printed form.

Defining & Creating the MySQL Database

Difficulty: Intermediate
Completion Time: 1 hour
What We Will Be Using: Pad And Paper, MySQL database (myPHPadmin)

Decide What Data To Collect
Before even getting into the MySQL database, we need to layout what information we will be collecting and how it should be stored. The best advice to be given here is to dream for the stars. Once the first version of the program is completed and sent out to be distributed, it will be an extreme pain to delete parts of the database and impossible to add new rows. If you think that there is even a remote chance that you will be using something, add it to the database now to be tested.

As an example, we realized that we would be collecting the title of the game, a description of how to play it, materials we needed, the date it was submitted, if the game is pending approval or ready to be displayed, and the always present unique game ID to track it in the database. We put this list down for a moment and began to see if we needed more tables or items to cover everything we wanted to do. After looking at our plan for an individual game, we realized we wanted to track the person who submits the game as well as a comment and rating system for each game.

Effectively Map Database Tables
After coming up with with a rough draft of what you want, it is time to begin testing. This is the perfect time to theoretically test the structures you have come up with on paper or a whiteboard. Display what information would be put into the database and then how you would like to see it displayed. This may have already been done in your planning if you were thorough enough. Look for any inconsistencies in your logic.

One thing that we noted when we went through this process is that we could not simply relate the comment ID to the game. One database style is to create the game and game type tables and then relate them to each other through a meta database. This meta will reference the a game time to a specific game, but still allow us to reference that same game to a different game type. This provides greater flexibility and eliminates any redundancy in data. (See the solution we came up with in the diagram at the end of the post)

Optimize Your Database
This is the time to go back through your draft of the database and see if you can optimize the different parts of your database. Should the title of each game be 256 characters long? Shortening it to 128 characters would speed up accessing data when someone loads a page on your website, but limit what people could call their games.

At this point, we need to make a judgement call, which is more important: download speeds or flexibility for the user? This is something that should be tracked and researched, even after the program has been written and distributed to others. Some of the best companies, Google and Microsoft, never get it right the first time, but consistent and effective tracking, analyzing, and improving their products have allowed them to create superior tools.

The final beta database we came up with is shown in the diagram below:

Writing A WordPress Plugin : 01 Planning

This week, we want to go through some of the initial steps we did of creating a WordPress plugin. WordPress started out as a simple blogging online application, but has developing into a widely used, open source, publishing system built on PHP and MySQL. From the beginning, WordPress has been structured for others to start with a framework and make the website their own, from adding custom themes to implementing their own plugins. A WordPress plugin is an application to provide a service, from a homepage photo slideshow to adding a sidebar widget to display the weather in a specific city.

Planning A Plugin

Difficulty: Easy
Completion Time: 1-6 hours
What We Will Be Using: Pad And Paper

We will be constructing a WordPress plugin that will collect youth ministry games from guest visitors, have a review display for the administrator, put them into a database, display in several forms to the users, and be searchable in many ways. This provides for many levels of PHP, MySQL, CSS, and logic engineering innovation. While several parts of the process to create this plugin will be proprietary, we will go over all the steps you will need to create a plugin for WordPress.

But to leave the planning process will make the process long and frustrating. We can press forward and envision what the parts of the website are going to look like. Nothing has to be perfect yet, but the more time you spend at this point of the process, the smoother and more streamlined the rest of the coding will go. At the same time, dream for the world and then you can take out what is not reasonable or could wait to be put into future versions.

All of the different people should have a say in this plugin: the client, designer, other programmers, and any financial people who should speak into it. Part of this process will be defining what the elements are and others parts are the workflow of the plugin. Grab a pen and paper or a whiteboard and many different colored markers with a couple of hours and just go crazy. Here are some great questions to think about in this process:

  • What do you want the plugin to do?
  • Is there already something out there that does what you want it to do?
  • What does this plugin NOT do?
  • Who will be coming to use this plugin?
  • What all do you want to be available to the administrator?
  • What general kinds of data do you want to be collecting, if any?
  • What are the different pages for this plugin (for the user and the administrator)?
  • Is there anything I do not have to reinvent?
  • What will the time tables and cost of this project be?

The next step will be to work with the MySQL database structure, which we will look at tomorrow.

Why Not Jetpack For WordPress

WordPress.com has recently made some serious changes, removing support for their wp-stats plugin and now pushing out their Jetpack WordPress plugin. The Jetpack plugin gives WordPress.com features to people who are running WordPress on their own servers. These features include:

  • A Twitter widget for displaying tweets in the sidebar
  • Gravatar Hovercard support
  • WordPress.com Stats
  • WP.me Shortlinks
  • LaTeX (an typesetting language)
  • Shortcode Embeds
  • Sharedaddy (social media bookmarks)
  • After the Deadline (grammar & spell check)


Sounds like a wonderful plugin that someone using it could not resist. But there are several bugs and problems with this plugin:

  • The Stats section requires that you have a working WordPress.com username and password whereas other WordPress statistic plugins do not need such a username. This is assumed to be because Automattic does not want to reveal how they collect stats or compile their graphs.
  • Jetpack has significant negative effects on server speeds. This website as well as others have noticed a loading lag after installing the plugin for testing that can accumulate in reduced performance.
  • Jetpack is bloated. They have not created something new but are trying to replace several individual plugins that work just as well. If you only want the stats and proofreading sections of Jetpack, you cannot individual download them.
  • Jetpack was created by Automattic, a FOR profit company funding WordPress.com and trying to walk the line of being free and still earning money. For now the plugin is free, but future features have already been guaranteed to be “premium” sections.
  • WordPress and Jetpack are starting to resemble the Mircosoft and Internet Explorer controversy because their one-click installations of WordPress at HostGator.com and Dreamhost.com come packaged with Jetpack and Akismet but exclude all other non-Automattic plugins.


So for now, we will not be hosting the Jetpack plugin and instead supporting the individual coders that meet our specific needs. We will see what comes of Jetpack, if they get rid of the bloating, the performance and WordPress.com account issues, and ever cross that “free” line.