WordPressプラグイン作成~データベースに設定情報を送れるようにする~
前回までで、管理画面で登録したい内容を入力する部分ができたので、
次は、実際にその入力した情報をデータとしてデータベースに保存するための記述を
追加していきます!
まずは、そもそも入力したデータを送信するためにボタン作っていきます。
formタグの中にinputタグでボタンを設置します。
今回記述していくファイルはこちら↓
\wp-content\plugins\dashicons-list-view\includes\dashicons-list-view-register.php
1 2 3 4 5 6 7 |
$html .= '<td><input type="text" name="pinterest_color" id="pinterest-color-picker"></td>'; $html .= '</tr>'; $html .= '</table>'; $html .= '<input type="submit" value="update" name="submit">'; $html .= '</form>'; $html .= '</div>'; echo $html; |
そして、いろいろ追加していきます。
WordPress nonces という、URL やフォームを悪用されないようにするために WordPress が生成する
一回限りのセキュリティトークンを入れていきます。
下記内容は、formタグの中に書きます。
セキュリティトークンに必要な
wp_nonce_field( ‘list_view_action’, ‘list_view_field’ );
は下記コードの7行目部分に書いてます。
ちなみに、2行目の部分では、optionsデータベースからデータを取得するための関数を書いていて、
取得したデータは$argsにいれてます。
1 2 3 4 5 6 7 8 9 10 11 |
private function page_render() { $args = get_option( $this->option ); $html = '<div class="wrap">'; $html .= '<h1>Dashicons List View Register</h1>'; $html .= '<form method="POST" action="">'; echo $html; wp_nonce_field( 'list_view_action', 'list_view_field' ); $html = '<table>'; $html .= '<tr>'; $html .= '<th> </th>'; $html .= '<th>Account</th>'; |
submitボタンを押してupdateボタンでsubmitされたら、
セットされてない時⇒exit
セットされている時⇒optionの内容でアップデートする
っていう内容を書いていきます。
1 2 3 4 5 6 7 8 9 10 |
private function update() { if ( isset ( $_POST['submit'] ) && $_POST['submit'] === 'update' ) { if ( ! isset( $_POST['list_view_field'] ) || ! wp_verify_nonce( $_POST['list_view_field'], 'list_view_action' ) ) { // print 'Sorry, your nonce did not verify.'; exit; } else { update_option( $this->option, $_POST ); } } } |
そして、実際に値が入ったら、その値をinputタグのvalue値に入れるように、
配列から取得できる内容を書きます。
Twitterのアカウント名部分が↓のような感じ。
1 |
$html .= '<td><input type="text" name="twitter_account" id="twitter_account" maxlength="30" value="' . $args['twitter_account'] . '"></td>'; |
あと、get_optionで取得しているoptionは、その前に、「’dashicons_list_view’」を取得しています。
update()関数を動かすための記述もしています。
1 2 3 4 5 6 |
class Dashicons_List_View_Register { private $option = 'dashicons_list_view'; public function __construct() { $this->update(); $this->page_render(); } |
そんな感じで実際に値を入れてupdateしてみると、
こんな感じになります。
▼管理画面上
▼データベース上(見やすいように改行してます)
データベース上に入れることができるようになったので、
次回は、実際にサイト上に載せるための内容を書いていきます。