Advertisement
  1. Code
  2. Creative Coding

Creating a Simple Backup/Restore Settings Feature

Scroll to top
Read Time: 10 min

Options are the most important data in WordPress, they store various configuration settings (see more). They're also contained in the database like other important data such as posts, pages, etc. Day by day, these options can be changed by WordPress itself or users. So how to configure them back to a previous state without memorizing each exact value?

In this tutorial, I'm going to show you how to create a simple backup/restore feature for your WordPress blog. With this feature, you can backup all options to another place, that you can restore them from at any time without configuring them again.


Before We Start

In general, our feature will have two sections, one is an Export section for backing up data and an Import section for restoring data. So I will demonstrate these by creating a simple plugin.


Step 1 Plugin Header

First of all, I must write a few lines to tell WordPress about our plugin.

1
2
/*

3
Plugin Name: I/E Option

4
Plugin URI: https://code.tutsplus.com

5
Description: This is a sample plugin with backup and restore options feature.

6
Author: Lee Pham

7
Version: 1.0

8
Author URI: http://twitter.com/leephamj

9
*/

And here is our result:


Step 2 Create a Page Admin

Now we need a place to put our plugin interface, it shows two key features that were mentioned above (including Import and Export features). So I generate a page in the admin section:

1
2
function register_ie_option() {
3
	add_menu_page('IE Option Page', 'IE Option', 'activate_plugins', 'ie-option', 'ie_option_page', '', 76);
4
	add_submenu_page('ie-option', 'Import', 'Import', 'activate_plugins', 'ie-import-option', 'ie_import_option_page');
5
	add_submenu_page('ie-option', 'Export', 'Export', 'activate_plugins', 'ie-export-option', 'ie_export_option_page');
6
}
7
8
function ie_option_page() {
9
	// Our stuff here

10
}
11
12
function ie_import_option_page() {
13
	// Content Import Feature

14
}
15
16
function ie_export_option_page() {
17
	// Content Export Feature

18
}
19
add_action('admin_menu', 'register_ie_option');

Here are some points:

  • We use add_menu_page as a built-in WordPress function to add a new top level menu section in the admin menu sidebar and where the ie_option_page parameter is the callback function for outputting the page content.
  • In order to separate two main features into different sections, we use add_submenu_page to add them to the top level menu we just created above. As you see, each function also has a callback function to display output content like the add_menu_page function does. It does not matters if you merge these into one place, I just try to keep it clear.
  • Then we hook register_ie_option on to the admin_menu action in order to trigger our goal everytime this action is called.

Step 3 Create Export Feature

I plan to create an Export page like this:

Create Export Page Skeleton

1
2
function ie_export_option_page() {
3
	if (!isset($_POST['export'])) {
4
		?>
5
		<div class="wrap">
6
			<div id="icon-tools" class="icon32"><br /></div>
7
			<h2>Export</h2>
8
			<p>When you click <tt>Backup all options</tt> button, system will generate a JSON file for you to save on your computer.</p>
9
			<p>This backup file contains all configution and setting options on our website. Note that it do <b>NOT</b> contain posts, pages, or any relevant data, just your all options.</p>
10
			<p>After exporting, you can either use the backup file to restore your settings on this site again or another WordPress site.</p>
11
			<form method='post'>
12
				<p class="submit">
13
					<?php wp_nonce_field('ie-export'); ?>
14
					<input type='submit' name='export' value='Backup all options'/>
15
				</p>
16
			</form>
17
		</div>
18
		<?php
19
	}
20
	elseif (check_admin_referer('ie-export')) {
21
		// Do something if Backup all options button clicked

22
	}
23
}

We just create a form with a button and check if the button is being clicked or not. Additionally, we add some instruction text using some available WordPress CSS class. For doing a security check, I use a wp_nonce_field() and the check_admin_referer() function, read more about WordPress Nonces.

Naming the Filename to Be Generated

1
2
$blogname = str_replace(" ", "", get_option('blogname'));
3
$date = date("m-d-Y");
4
$json_name = $blogname."-".$date;

Just name the file so you can easily see where and when it was exported.

Get Backup Options and Encode Into JSON Data

1
2
$options = get_alloptions();
3
4
foreach ($options as $key => $value) {
5
	$value = maybe_unserialize($value);
6
	$need_options[$key] = $value;
7
}
8
9
$json_file = json_encode($need_options);

Here is the important step, let's pay attention:

  • get_alloptions() is a function that gets all options on your site and returns them as an array, $options in this case.
  • By retrieving all the options, the value of options may be serialized data, so we have to unserialize it first.
  • Our intention is to generate JSON to store the backup data. JSON is a light-weight and powerful way to store text information. So what we need to do is convert our data to JSON syntax, json_encode helps us to achieve this goal.
1
2
ob_clean();
3
echo $json_file;
4
header("Content-Type: text/json; charset=" . get_option( 'blog_charset'));
5
header("Content-Disposition: attachment; filename=$json_name.json");
6
exit();

Then we wrap content of our JSON data within two important functions, ob_clean() and exit() to ensure our generated JSON file only contains JSON data that json_file holds without any other data. By the way, we send a header request to the client that displays a download dialog. To make this work properly we should put the ob_start() function at the top of our plugin code, this prevents header errors from occurring, maybe there are some extra whitespace or lines somewhere in WordPress code that could cause that.

"JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate."

So here is the entire Export function code:

1
2
function ie_export_option_page() {
3
	if (!isset($_POST['export'])) {
4
		?>
5
		<div class="wrap">
6
			<div id="icon-tools" class="icon32"><br /></div>
7
			<h2>Export</h2>
8
			<p>When you click <tt>Backup all options</tt> button, system will generate a JSON file for you to save on your computer.</p>
9
			<p>This backup file contains all configution and setting options on our website. Note that it do <b>NOT</b> contain posts, pages, or any relevant data, just your all options.</p>
10
			<p>After exporting, you can either use the backup file to restore your settings on this site again or another WordPress site.</p>
11
			<form method='post'>
12
				<p class="submit">
13
					<?php wp_nonce_field('ie-export'); ?>
14
					<input type='submit' name='export' value='Backup all options'/>
15
				</p>
16
			</form>
17
		</div>
18
		<?php
19
	}
20
	elseif (check_admin_referer('ie-export')) {
21
22
		$blogname = str_replace(" ", "", get_option('blogname'));
23
		$date = date("m-d-Y");
24
		$json_name = $blogname."-".$date; // Namming the filename will be generated.

25
26
		$options = get_alloptions(); // Get all options data, return array

27
28
		foreach ($options as $key => $value) {
29
			$value = maybe_unserialize($value);
30
			$need_options[$key] = $value;
31
		}
32
33
		$json_file = json_encode($need_options); // Encode data into json data

34
35
		ob_clean();
36
		echo $json_file;
37
		header("Content-Type: text/json; charset=" . get_option( 'blog_charset'));
38
		header("Content-Disposition: attachment; filename=$json_name.json");
39
		exit();
40
	}
41
}

Step 4 Create Import Feature

This page's task is quite simple, it displays an upload form and parses data from the JSON file to backup our options.

Create Import Page Skeleton

1
2
function ie_import_option_page() {
3
	?>
4
	<div class="wrap">
5
		<div id="icon-tools" class="icon32"><br /></div>
6
		<h2>Import</h2>
7
		<?php
8
			if (isset($_FILES['import'])) {
9
				// Do something if a file was uploaded

10
			}
11
		?>
12
		<p>Click Browse button and choose a json file that you backup before.</p>
13
		<p>Press Restore button, WordPress do the rest for you.</p>
14
		<form method='post' enctype='multipart/form-data'>
15
			<p class="submit">
16
				<?php wp_nonce_field('ie-import'); ?>
17
				<input type='file' name='import' />
18
				<input type='submit' name='submit' value='Restore'/>
19
			</p>
20
		</form>
21
	</div>
22
	<?php
23
}

Like the Export page we create a form, but this time, we add a Browse button so the user can choose the file they want and submit it.

Validation and Updating JSON File

1
2
if (isset($_FILES['import'])) {
3
	if ($_FILES['import']['error'] > 0) {
4
		wp_die("Error happens");
5
	}
6
	else {
7
		$file_name = $_FILES['import']['name'];
8
		$file_ext = strtolower(end(explode(".", $file_name)));
9
		$file_size = $_FILES['import']['size'];
10
		if (($file_ext == "json") && ($file_size < 500000)) {
11
			$encode_options = file_get_contents($_FILES['import']['tmp_name']);
12
			$options = json_decode($encode_options, true);
13
			foreach ($options as $key => $value) {
14
				update_option($key, $value);
15
			}
16
			echo "<div class='updated'><p>All options are restored successfully.</p></div>";
17
		}
18
		else {
19
			echo "<div class='error'><p>Invalid file or file size too big.</p></div>";
20
		}
21
	}
22
}

If the upload process gets errors, just return a die message "An error has occurred". If not, get the extension and size of the file, store them into variables and check them. We only accept files that have the ".json" extension and size of less than 500000 bytes. If the file is not an appropriate one, just display an error message "Invalid file or file size too big.". Note: You can modify this size as you need.

Then, the $encode_options variable will get all content of this file. As the file contains JSON data, before using it we must decode first. To do this, we use json_decode with a second parameter that has a true value so this function returns an array value. With an array value, we start to loop over it. On each iteration, we will update data with the same key and its value. In the end, all our options will be restored exactly as they were, and a successful message will be displayed.

And here is the entire Import function code:

1
2
function ie_import_option_page() {
3
	?>
4
	<div class="wrap">
5
		<div id="icon-tools" class="icon32"><br /></div>
6
		<h2>Import</h2>
7
		<?php
8
			if (isset($_FILES['import']) && check_admin_referer('ie-import')) {
9
				if ($_FILES['import']['error'] > 0) {
10
					wp_die("Error happens");
11
				}
12
				else {
13
					$file_name = $_FILES['import']['name']; // Get the name of file

14
					$file_ext = strtolower(end(explode(".", $file_name))); // Get extension of file

15
					$file_size = $_FILES['import']['size']; // Get size of file

16
					/* Ensure uploaded file is JSON file type and the size not over 500000 bytes

17
 					 * You can modify the size you want

18
					 */
19
					if (($file_ext == "json") && ($file_size < 500000)) {
20
						$encode_options = file_get_contents($_FILES['import']['tmp_name']);
21
						$options = json_decode($encode_options, true);
22
						foreach ($options as $key => $value) {
23
							update_option($key, $value);
24
						}
25
						echo "<div class='updated'><p>All options are restored successfully.</p></div>";
26
					}
27
					else {
28
						echo "<div class='error'><p>Invalid file or file size too big.</p></div>";
29
					}
30
				}
31
			}
32
		?>
33
		<p>Click Browse button and choose a json file that you backup before.</p>
34
		<p>Press Restore button, WordPress do the rest for you.</p>
35
		<form method='post' enctype='multipart/form-data'>
36
			<p class="submit">
37
				<?php wp_nonce_field('ie-import'); ?>
38
				<input type='file' name='import' />
39
				<input type='submit' name='submit' value='Restore'/>
40
			</p>
41
		</form>
42
	</div>
43
	<?php
44
}

Create Your Own Backup Feature for Your Templates or Plugins

In the sample plugin, I backed up all of the site options by using the get_alloptions WordPress function. If you want to apply this to your own specific options, just do it like this:

1
2
$options = array('your_option1_name' => get_option('your_option1_name'), 'your_option2_name' => get_option('your_option2_name');
3
$json_file = json_encode($options);

And go on to the next step as above. You freely choose what options you want to backup!


Conclusion

In this tutorial, we take a look at an overview of creating a simple backup/restore feature. You should notice that my plugin is just a simple sample not an official one. My goal is not write a perfect plugin, but to show you the basic principle of this feature. By understanding it, you can create your own feature on your templates or plugins, you also can make it as flexible as you want. Therefore you can make this feature isolated for your templates/plugins.

I hope this tutorial is useful for you, let me know what you think. Your ideas make it better, or even show me my mistakes, your feedback will really help a lot. Thanks for reading!


Preference:

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.