Home > Article > Backend Development > Simplify the process of backing up and restoring settings
Options are the most important data in WordPress, they store various configuration settings (see more). They are also included in the database like other important data like posts, pages, etc. From day to day, these options can be changed by WordPress itself or by the user. So how do you configure them back to their previous state without remembering every exact value?
In this tutorial, I will show you how to create a simple backup/restore functionality for your WordPress blog. Using this feature, you can back up all your options to another location from which you can restore them at any time without having to configure them again.
Generally speaking, our function will be divided into two parts, an export part for backing up data and an import part for restoring data. So I'm going to demonstrate these by creating a simple plugin.
First, I have to write a few lines to tell WordPress about our plugin.
/* Plugin Name: I/E Option Plugin URI: https://code.tutsplus.com Description: This is a sample plugin with backup and restore options feature. Author: Lee Pham Version: 1.0 Author URI: http://twitter.com/leephamj */
Here are our results:
Now we need a place to put our plugin interface, which displays the two key functions mentioned above (including import and export functions). So I generate a page in the admin section:
function register_ie_option() { add_menu_page('IE Option Page', 'IE Option', 'activate_plugins', 'ie-option', 'ie_option_page', '', 76); add_submenu_page('ie-option', 'Import', 'Import', 'activate_plugins', 'ie-import-option', 'ie_import_option_page'); add_submenu_page('ie-option', 'Export', 'Export', 'activate_plugins', 'ie-export-option', 'ie_export_option_page'); } function ie_option_page() { // Our stuff here } function ie_import_option_page() { // Content Import Feature } function ie_export_option_page() { // Content Export Feature } add_action('admin_menu', 'register_ie_option');
Here are some key points:
add_menu_page
as a built-in WordPress function to add a new top-level menu section in the admin menu sidebar, where the ie_option_page
parameter is the callback function used to output the page content. add_submenu_page
to add them to the top-level menu we just created above. As you can see, each function also has a callback function to display the output, just like the add_menu_page
function. It doesn't matter if you merge them into one place, I just try to keep it clear. register_ie_option
to the admin_menu
action so that our target is triggered every time this action is called. I plan to create an export page like this:
function ie_export_option_page() { if (!isset($_POST['export'])) { ?> <div class="wrap"> <div id="icon-tools" class="icon32"><br /></div> <h2>Export</h2> <p>When you click <tt>Backup all options</tt> button, system will generate a JSON file for you to save on your computer.</p> <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> <p>After exporting, you can either use the backup file to restore your settings on this site again or another WordPress site.</p> <form method='post'> <p class="submit"> <?php wp_nonce_field('ie-export'); ?> <input type='submit' name='export' value='Backup all options'/> </p> </form> </div> <?php } elseif (check_admin_referer('ie-export')) { // Do something if Backup all options button clicked } }
We just create a form with a button and check if the button is clicked. Additionally, we add some descriptive text using some of the available WordPress CSS classes. For security checks, I use the wp_nonce_field()
and check_admin_referer()
functions. Learn more about WordPress Nonces.
$blogname = str_replace(" ", "", get_option('blogname')); $date = date("m-d-Y"); $json_name = $blogname."-".$date;
Just give the file a name so you can easily see where and when it was exported.
$options = get_alloptions(); foreach ($options as $key => $value) { $value = maybe_unserialize($value); $need_options[$key] = $value; } $json_file = json_encode($need_options);
This is an important step, please pay attention:
get_alloptions()
is a function that gets all the options on the site and returns them as an array, in this case $options
. json_encode
helps us achieve this goal. ob_clean(); echo $json_file; header("Content-Type: text/json; charset=" . get_option( 'blog_charset')); header("Content-Disposition: attachment; filename=$json_name.json"); exit();
We then wrap the contents of the JSON data in two important functions, ob_clean()
and exit()
to ensure that the generated JSON file only contains json_file
Saved JSON data without any other data. By the way, we send a header request to the client to display a download dialog. In order for it to work properly we should put the ob_start()
function at the top of the plugin code, this will prevent header errors from happening, maybe there are some extra spaces or lines somewhere in the WordPress code can cause this situation. p>
"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."
This is the complete export function code:
function ie_export_option_page() { if (!isset($_POST['export'])) { ?> <div class="wrap"> <div id="icon-tools" class="icon32"><br /></div> <h2>Export</h2> <p>When you click <tt>Backup all options</tt> button, system will generate a JSON file for you to save on your computer.</p> <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> <p>After exporting, you can either use the backup file to restore your settings on this site again or another WordPress site.</p> <form method='post'> <p class="submit"> <?php wp_nonce_field('ie-export'); ?> <input type='submit' name='export' value='Backup all options'/> </p> </form> </div> <?php } elseif (check_admin_referer('ie-export')) { $blogname = str_replace(" ", "", get_option('blogname')); $date = date("m-d-Y"); $json_name = $blogname."-".$date; // Namming the filename will be generated. $options = get_alloptions(); // Get all options data, return array foreach ($options as $key => $value) { $value = maybe_unserialize($value); $need_options[$key] = $value; } $json_file = json_encode($need_options); // Encode data into json data ob_clean(); echo $json_file; header("Content-Type: text/json; charset=" . get_option( 'blog_charset')); header("Content-Disposition: attachment; filename=$json_name.json"); exit(); } }
The task of this page is very simple, it displays the upload form and parses the data in the JSON file to back up our options.
function ie_import_option_page() { ?> <div class="wrap"> <div id="icon-tools" class="icon32"><br /></div> <h2>Import</h2> <?php if (isset($_FILES['import'])) { // Do something if a file was uploaded } ?> <p>Click Browse button and choose a json file that you backup before.</p> <p>Press Restore button, WordPress do the rest for you.</p> <form method='post' enctype='multipart/form-data'> <p class="submit"> <?php wp_nonce_field('ie-import'); ?> <input type='file' name='import' /> <input type='submit' name='submit' value='Restore'/> </p> </form> </div> <?php }
与导出页面一样,我们创建了一个表单,但这次,我们添加了一个浏览按钮,以便用户可以选择他们想要的文件并提交。
if (isset($_FILES['import'])) { if ($_FILES['import']['error'] > 0) { wp_die("Error happens"); } else { $file_name = $_FILES['import']['name']; $file_ext = strtolower(end(explode(".", $file_name))); $file_size = $_FILES['import']['size']; if (($file_ext == "json") && ($file_size < 500000)) { $encode_options = file_get_contents($_FILES['import']['tmp_name']); $options = json_decode($encode_options, true); foreach ($options as $key => $value) { update_option($key, $value); } echo "<div class='updated'><p>All options are restored successfully.</p></div>"; } else { echo "<div class='error'><p>Invalid file or file size too big.</p></div>"; } } }
如果上传过程出错,只需返回一条死消息“发生错误”。如果没有,获取文件的扩展名和大小,将它们存储到变量中并检查它们。我们只接受扩展名为“.json”且大小小于 500000 字节的文件。如果文件不合适,则仅显示一条错误消息“文件无效或文件大小太大。”。 注意:您可以根据需要修改此尺寸。
然后,$encode_options
变量将获取该文件的所有内容。由于文件中包含JSON数据,因此在使用之前我们必须先解码。为此,我们使用 json_decode
和具有 true 值的第二个参数,因此该函数返回一个数组值。有了数组值,我们就开始循环它。在每次迭代中,我们将使用相同的键及其值更新数据。最后,我们的所有选项都将完全恢复原样,并显示一条成功消息。
这是完整的导入功能代码:
function ie_import_option_page() { ?> <div class="wrap"> <div id="icon-tools" class="icon32"><br /></div> <h2>Import</h2> <?php if (isset($_FILES['import']) && check_admin_referer('ie-import')) { if ($_FILES['import']['error'] > 0) { wp_die("Error happens"); } else { $file_name = $_FILES['import']['name']; // Get the name of file $file_ext = strtolower(end(explode(".", $file_name))); // Get extension of file $file_size = $_FILES['import']['size']; // Get size of file /* Ensure uploaded file is JSON file type and the size not over 500000 bytes * You can modify the size you want */ if (($file_ext == "json") && ($file_size < 500000)) { $encode_options = file_get_contents($_FILES['import']['tmp_name']); $options = json_decode($encode_options, true); foreach ($options as $key => $value) { update_option($key, $value); } echo "<div class='updated'><p>All options are restored successfully.</p></div>"; } else { echo "<div class='error'><p>Invalid file or file size too big.</p></div>"; } } } ?> <p>Click Browse button and choose a json file that you backup before.</p> <p>Press Restore button, WordPress do the rest for you.</p> <form method='post' enctype='multipart/form-data'> <p class="submit"> <?php wp_nonce_field('ie-import'); ?> <input type='file' name='import' /> <input type='submit' name='submit' value='Restore'/> </p> </form> </div> <?php }
在示例插件中,我使用 get_alloptions
WordPress 函数备份了所有站点选项。如果您想将其应用于您自己的特定选项,只需这样做:
$options = array('your_option1_name' => get_option('your_option1_name'), 'your_option2_name' => get_option('your_option2_name'); $json_file = json_encode($options);
然后继续执行上述下一步。您可以自由选择要备份的选项!
在本教程中,我们将概述创建简单的备份/恢复功能。您应该注意到,我的插件只是一个简单的示例,而不是官方的。我的目标不是写一个完美的插件,而是向你展示这个功能的基本原理。通过理解它,您可以在模板或插件上创建自己的功能,也可以根据需要使其灵活。因此,您可以为您的模板/插件隔离此功能。
我希望本教程对您有用,请告诉我您的想法。你的想法让它变得更好,甚至告诉我我的错误,你的反馈真的会有很大帮助。感谢您的阅读!
add_menu_page
WordPress 函数add_submenu_page
WordPress函数get_alloptions
WordPress 函数The above is the detailed content of Simplify the process of backing up and restoring settings. For more information, please follow other related articles on the PHP Chinese website!