這一篇為大家講解如何將資料儲存到資料庫中,並且顯示在頁面上,不會因提交表單時重新整理頁面輸入框中內容消失。要實現這一功能我們需要藉助 WordPress 函式來實現,下面就來講解具體的實現方法,先把程式碼貼出來。還是根據之前的那個外掛樣例,大家可以直接在上面做修改。
<?php
//在 WordPress 後臺評論處顯示一個子選單出來
add_action('admin_menu', 'my_plugin_menu2');
function my_plugin_menu2() {
add_comments_page('資料儲存', '資料儲存', 'read', 'my-unique-identifier','my_plugin_function2');
}
function my_plugin_function2()
{
if($_POST['test_hidden'] == 'y')
{
update_option('test_input_c',$_POST['test_input']);
//更新你新增的資料庫
?>
<div id="message" > 儲存成功!</div>
<?php
}
?>
<div >
<?php screen_icon(); //顯示圖示 ?>
<h2> 新增資料</h2>
<p> 在這裡進行資料新增。</p>
<form action="" method="post" id="my_plugin_test_form">
<h3>
<label for="test_input"> 測試資料:</label>
<input type="text" id="test_input" name="test_input" value="<?php echo esc_attr(get_option('test_input_c')); ?>" />
<h3>
<p>
<input type="submit" name="submit" value="儲存" />
<input type="hidden" name="test_hidden" value="y" />
</p>
</form>
</div>
<?php
}
//透過 get_option() 來顯示存在資料庫中的資訊。
//以上填寫的資訊都存在了資料庫中的 wp_options 表裡面。
?>
上面簡短的程式碼就實現了資料儲存並顯示的功能,透過這個功能我們就可以延伸到其他的方法或者功能上面。比如一些不錯的主題都帶有主題設定,裡面的一些顯示和儲存都可以用上面的方法來實現,大家可以多多去嘗試下。大概效果就如下面的樣例圖。

好了這篇文章就寫到這裡了,如果有不明白或者好的建議的多多提問和指導哦。