Any Questions?

02476 252 345

How to Save Plugin Information to the WordPress Database (WP Series Part Six)

Writing to the database

Happy Monday WordPress developers. Today we will be looking at saving and retrieving information from the WordPress database. We finished the last tutorial off by correctly adding the markup for our plugins page. As you can see our plugin is beginning to take shape, however currently it still doesn’t save data. This is what we will be tackling today.

Working with Forms

I am going to assume that you have basic knowledge of how HTML forms work. WordPress uses the POST method over GET to ensure data is sent straight to the server rather than through the URL.

Validating the form

For security reasons I have added a hidden field into our code, if you take a quick look over the code provided in the last tutorial you should be able to see before the submit button that I have added a hidden input field with the value of “Y”. This will allow us to monitor whether the form has been submitted or not within our code.

<input name="mash_form_submitted" type="hidden" value="Y" />

Validating our hidden input field

If we head over to our mash-general-info.php file, and find our options page function we will be inserting the following code inside the if statement that checks whether the user can manage options. The reason we are doing this is to check whether the form has been submitted and if it has to run a series of commands. We will first be checking whether mash_form_submitted field exists using the php function isset, this will check whether the form has been submitted. If it does exist we will save the hidden input field value inside a variable and check whether it is equal to the value “Y”. It is important that we ensure this level of validation with our forms, otherwise we could end up with users inserting malicious code into the database from our plugin.

 function mash_general_info_options(){

      if(current_user_can('manage_options')):

	  		if(isset($_POST['mash_form_submitted'])){

				$hidden = esc_html($_POST['mash_form_submitted']);

					if($hidden == 'Y'){

						$hidden = $_POST['mash_dynamic_telephone'];

					}

			}

           require('includes/options-page.php');

Some of you may have noticed that where we have set our variable $hidden to the value of mash_form_submitted, we have also included another function called esc_html(). This PHP function ensures that we escape any HTML tags from the input field, the reason we do this is to ensure that no one has entered any malicious data in the field that could potentially corrupt our database.

Retrieving submitted form values.

So now we have added some basic validation to our form that checks whether it has been submitted or not lets try to echo out a submitted telephone value.

    if($hidden == 'Y'){
         echo $_POST['mash_dynamic_telephone'];
    }

If you now head back to to our options page, fill in the telephone field and save the form you should be able to see the value you entered echoed at the top of the plugins page. Now we know how to accept form data, all we need to do now is to store the data.

Storing Data in the Options Table

We will be storing our data in the database table wp_options, WordPress has built in functions that helps developers store data without writing pure SQL. WordPress provides the following functions:

  • add_option(‘options_name’, ‘options_value’);
  • get_option(‘option_name’);
  • update_option(‘option_name’, ‘option_value’);
  • delete_option(‘option_name’);

By knowing just the above four functions and how to implement them correctly we have expanded our plugin development knowledge dramatically. You should be able to see that we actually do not need to provide many parameters in order to manipulate data straight from the database. Lets head over to our file and try our our new functions. Lets begin by removing our echo statement and instead add the following code.

    $mash_tel = $_POST['mash_dynamic_telephone'];
    update_option('mash_general_info_telephone', $mash_tel);
    echo get_option('mash_general_info_telephone');

What we have done above is simply create a variable named $mash_tel set it the value of the telephone field and then ran the update_option function specifying the row we would like to add or update as well as the variable we would like to insert. Then by using the get_option function we have retrieved the telephone number and echoed it out onto the page. If we save this, head over to our plugin insert a telephone number and save it, we should see our value echoed out onto the page like before. The main difference is if you were to now log out and log back in our value will still be stored and echoed out.

How to store an array into the WordPress Database

You now know how to add data to the database, we could go ahead and add all of our other fields to the database to individually. However lets consider the fact that by doing it individually we will need 12 different rows within our database. Wouldn’t it be much more efficient to have one row that contains all of the data. Luckily for us we can store all of our data inside an array and insert this into the database. MySQL doesn’t except arrays unless they have been serialized, luckily for us the WordPress functions we are using looks after this which means we don’t have to. Example of an array

    array(
        key  => value,
        key2 => value2,
        key3 => value3,
        ...
    )

An Example of a serialized array

a:3:{i:1;s:6:"value";i:2;s:6:"value2";i:3;s:7:" value3";}

Now that we know that we can store all of our data within an array, lets go ahead an remove the option we created in the database by using the delete_option() function.

   delete_option('mash_general_info_telephone');

We can now begin to create our array of values and store them in an $options array. To do this we firstly need to create a global array so we can use it throughout our functions. Lets begin by creating our array at the top of our mash-general-info.php file below our WordPress comments.

 /*Global Variables*/

 $options = array();

Now lets head down into the function that controls our plugins page and add our global array.

function mash_general_info_options(){

	 	if(current_user_can('manage_options')):

		global  $options;

		if(isset($_POST['mash_form_submitted'])){

We can now access this global variable from our function and inside our options-page.php. Inside our if statement that checks whether the hidden input field equals ‘Y’ we need to create a variable for each individual input field, and then store each variable inside our array with a appropriate key. We could skip the first part where we create the variables and directly insert the values from the $_POST into our array however i find by creating individual variables it is making our code a lot easier to read and it also allows us to call upon the variables in our code later on. Once we have our array in place, we need to insert the data into the database the same as we did before. We will be calling the update_option() function again to insert the array into the database under the database row mash_general_info. By looking at the code below you should be able to notice that i have also called the function get_option(‘mash_general_info’) and stored the data into my $options array. By doing this we will be able to access all of our data stored in the database.


if(isset($_POST['mash_form_submitted'])){

     $hidden = esc_html($_POST['mash_form_submitted']);

     if($hidden == 'Y'){

          $mash_tel = $_POST['mash_dynamic_telephone'];
          $mash_tel_2 = $_POST['mash_dynamic_telephone_2'];
          $mash_add_1 = $_POST['mash_dynamic_address_1'];
          $mash_add_2 = $_POST['mash_dynamic_address_2'];
          $mash_add_3 = $_POST['mash_dynamic_address_3'];
          $mash_add_4 = $_POST['mash_dynamic_address_4'];
          $mash_email = $_POST['mash_dynamic_email'];
          $mash_strapline = $_POST['mash_dynamic_strapline'];
          $mash_twitter = $_POST['mash_dynamic_twitter_url'];
          $mash_facebook = $_POST['mash_dynamic_facebook_url'];
          $mash_google = $_POST['mash_dynamic_google_url'];
          $mash_youtube = $_POST['mash_dynamic_youtube_url'];

          $options['telephone'] = $mash_tel;
          $options['telephone_2'] = $mash_tel_2;
          $options['address_1'] = $mash_add_1;
          $options['address_2'] = $mash_add_2;
          $options['address_3'] = $mash_add_3;
          $options['address_4'] = $mash_add_4;
          $options['email'] = $mash_email;
          $options['strapline'] = $mash_strapline;
          $options['twitter_url'] = $mash_twitter;
          $options['facebook_url'] = $mash_facebook;
          $options['google_url'] = $mash_google;
          $options['youtube_url'] = $mash_youtube;
          $options['last_updated'] = time();

          update_option('mash_general_info', $options);
    }	

}
	  $options = get_option('mash_general_info');

Retrieving all of our option values

Lets attempt to retrieve all of our values, we now have the data stored in our variable $options, so all we need to do is access it. This is extremely simple to do as we defined keys for our values. All we need to do is echo the $options variable and provide the relevant key. Lets give this a try on our options page. Open up options-page.php and replace the form with the following code. The only difference are that we have now provided an echo statement for the value of our fields.

</pre>
<form action="" method="post" name="mash_general_options_form">
<table class="form-table">
<tbody>
<tr>
<td><label for="mash_dynamic_telephone">Telephone</label></td>
<td><input id="mash_dynamic_telephone" class="regular-text" name="mash_dynamic_telephone" type="text" value="<?php echo $options['telephone']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_telephone_2">Telephone Two</label></td>
<td><input id="mash_dynamic_telephone_2" class="regular-text" name="mash_dynamic_telephone_2" type="text" value="<?php echo $options['telephone_2']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_address_1">Address Line 1</label></td>
<td><input id="mash_dynamic_address_1" class="regular-text" name="mash_dynamic_address_1" type="text" value="<?php echo $options['address_1']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_address_2">Address Line 2</label></td>
<td><input id="mash_dynamic_address_2" class="regular-text" name="mash_dynamic_address_2" type="text" value="<?php echo $options['address_2']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_address_3">Address Line 3</label></td>
<td><input id="mash_dynamic_address_3" class="regular-text" name="mash_dynamic_address_3" type="text" value="<?php echo $options['address_3']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_address_4">Address Line 4</label></td>
<td><input id="mash_dynamic_address_4" class="regular-text" name="mash_dynamic_address_4" type="text" value="<?php echo $options['address_4']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_email">Email Address</label></td>
<td><input id="mash_dynamic_email" class="regular-text" name="mash_dynamic_email" type="text" value="<?php echo $options['email']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_strapline">Website Strapline</label></td>
<td><input id="mash_dynamic_strapline" class="regular-text" name="mash_dynamic_strapline" type="text" value="<?php echo $options['strapline']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_twitter_url">Twitter URL</label></td>
<td><input id="mash_dynamic_twitter_url" class="regular-text" name="mash_dynamic_twitter_url" type="text" value="<?php echo $options['twitter_url']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_facebook_url">Facebook URL</label></td>
<td><input id="mash_dynamic_facebook_url" class="regular-text" name="mash_dynamic_facebook_url" type="text" value="<?php echo $options['facebook_url']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_google_url">Google Plus URL</label></td>
<td><input id="mash_dynamic_google_url" class="regular-text" name="mash_dynamic_google_url" type="text" value="<?php echo $options['google_url']; ?>" /></td>
<td></td>
</tr>
<tr>
<td><label for="mash_dynamic_youtube_url">Youtube URL</label></td>
<td><input id="mash_dynamic_youtube_url" class="regular-text" name="mash_dynamic_youtube_url" type="text" value="<?php echo $options['youtube_url']; ?>" /></td>
<td></td>
</tr>
</tbody>
</table>
<input name="mash_form_submitted" type="hidden" value="Y" /> <input class="button-primary" name="mash-form_submit" type="submit" value="<?php _e( 'Save Information' ); ?>" /></form>
<pre>

Bringing it all together

Now our values added should reappear within our fields once they have been submitted, this is a very popular technique and it shows the user what they have previously entered. So you can now add, edit and delete from the database all what is left to do is for us to be able to pull this information out into our theme.

Written by:

Creative Director - info@mash-webdesign.co.uk - 07541987924 - DOB: 02/1993/27

With over five years commercial experience in the web industry, Adam specialises in all things web related. Adam has a passion for CRO, ensuring that the websites he creates don't just look great but also make his clients money.

Mash Web Design