WordPress のカスタム データベース テーブル: パート 2

公開: 2022-08-01

WordPress のカスタム データベース テーブルに関するシリーズの最初の部分では、独自のカスタム プラグイン内からカスタム データベース テーブルを作成する方法を見てきました。 パート 2 では、プラグインの削除時にカスタム データベース テーブルを削除する方法など、WordPress カスタム テーブルを変更する方法について説明します。 さらに、カスタム データ テーブルのエントリを表示または追加するオプションを使用して、管理領域にプラグインのメニュー項目を追加する方法についても説明します。

プラグインの削除時にカスタム テーブルを削除する方法

プラグイン自体が削除されたときにテーブルを削除するには、WordPress がプラグインのアンインストール フックを設定するために提供するregister_uninstall_hook()関数を使用する必要があります。

 function uninstall_students_plugin(){ global $wpdb; $table_name = $wpdb->prefix . 'students'; $wpdb->query("DROP TABLE IF EXISTS $table_name"); } register_uninstall_hook(__FILE__,'uninstall_students_plugin');

ここでプラグインを非アクティブ化して削除すると、データベースの「students」テーブルが正常に削除されたことがわかります。

カスタム テーブル管理メニュー項目とページ

このセクションでは、「学生」カスタム テーブルの管理ページとそのメニュー項目を追加する方法を説明します。

管理メニュー項目

試してみることができるコードは次のとおりです。現在のプラグイン PHP ファイルに追加します。

 function students_custom_table_admin_menu() { add_menu_page(__('Students', 'students_custom_table'), __('Students', 'students_custom_table'), 'activate_plugins', 'students', 'students_custom_table_page_handler', 'dashicons-welcome-learn-more', '5'); add_submenu_page('students', __('Students', 'students_custom_table'), __('Students', 'students_custom_table'), 'activate_plugins', 'students', 'students_custom_table_page_handler'); add_submenu_page('students', __('Add new', 'students_custom_table'), __('Add new', 'students_custom_table'), 'activate_plugins', 'students_form', 'students_custom_table_page_handler_add_form'); } add_action('admin_menu', 'students_custom_table_admin_menu');

管理エリアに、このようなものが表示されるはずです。

予想どおり、どのアイコンをクリックしても何も表示されないことがわかります。 次のセクションでページの内容を定義しますが、まず、上記のコード行を調べて、それらがどのように機能するかを理解しましょう。

Pressidium でウェブサイトをホストする

60日間の返金保証

プランを見る

トップレベルのメニュー項目と 2 つのサブ項目を作成したいので、WordPress が提供する add_menu_page() 関数と add_submenu_page() 関数の両方を使用しました。 これらの関数は、次の引数を受け入れます。

 add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position )
  • $page_titleを定義する必要があり、これは基本的に、このメニュー項目を選択したときにリダイレクトされるページのタイトル タグの最初の部分です。 私たちの場合、 students_custom_table .
  • $menu_title (これも必須) は、メニューに使用されるテキストです。 テキストは「学生」を選びました。
  • $capabilityは、ユーザーがこのメニューを表示するために必要な機能です。 私たちの場合、 activate_pluginsパーミッションを選択しました。 デフォルトでは、スーパー ユーザーと管理者のみに付与されます。 どのロールまたは機能がニーズに合っているかを理解したい場合は、関連する公式ドキュメントを参照してください。
  • $menu_slugは、許可の直後にあるstudents文字列です。 これも必須で、一意である必要があります。 これは、sanitize_key() と互換性のある小文字の英数字、ダッシュ、およびアンダースコア文字のみを使用します。
  • $icon_urlはオプションの引数で、メニュー項目に使用されるアイコン ファイルにリンクする URL です。 dashicons WordPress ライブラリから 1 つを選択しました。
  • $position は、オプションで、この項目が表示されるメニュー順序の位置を設定する場所です。
 add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position )

add_menu_pageと共通のパラメーター以外にも、

  • $parent_slugパラメーターは、親メニュー (この場合はstudents ) に必要な文字列です。
  • $function引数は、設定ページのコンテンツを作成するコールバック関数を定義する場所です。 私たちの場合、学生表示テーブル用の students_custom_table_page_handler students_custom_table_page_handler() students_custom_table_page_handler_add_form()です。
    これらの関数はまだ宣言していませんが、そのうち宣言します。

カスタム テーブル レコードの表示

「学生」メニュー項目の下に学生テーブルを表示するコードを追加することから始めましょう。

管理テーブルのデータを表示するために、WordPress はWP_List_Table組み込みクラスを拡張します。 WP_List_Tableクラスは、wp-admin/includes/class-wp-list-table.php ファイルでプライベート クラスとして導入されます。 プライベート クラスは、開発者ではなく、他のコア クラスおよび関数による使用のみを目的としているため、プライベートと呼ばれます。

ただし、WordPress では、このクラスを拡張して再定義することができます。 そこで、管理テーブルに必要なデータを入力するために、 WP_List_Tableクラスのプロパティとメソッドを再定義するカスタム クラスを作成します。 クラスに「Students_Custom_Table_List_Table」という名前を付けました。必要なコード行は次のとおりです。

 if (!class_exists('WP_List_Table')) { require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php'); } class Students_Custom_Table_List_Table extends WP_List_Table { function __construct() { global $status, $page; parent::__construct(array( 'singular' => 'person', 'plural' => 'persons', )); } function column_default($item, $column_name) { return $item[$column_name]; } function column_age($item) { return '<em>' . $item['age'] . '</em>'; } function column_ip($item) { return '<em>' . $item['ip_address'] . '</em>'; } function column_name($item) { $actions = array( 'edit' => sprintf('<a href="?page=students_form&id=%s">%s</a>', $item['id'], __('Edit', 'students_custom_table')), 'delete' => sprintf('<a href="?page=%s&action=delete&id=%s">%s</a>', $_REQUEST['page'], $item['id'], __('Delete', 'students_custom_table')), ); return sprintf('%s %s', $item['name'], $this->row_actions($actions) ); } function column_cb($item) { return sprintf( '<input type="checkbox" name="id[]" value="%s" />', $item['id'] ); } function get_columns() { $columns = array( 'cb' => '<input type="checkbox" />', //Render a checkbox instead of text 'name' => __('Name', 'students_custom_table'), 'email' => __('E-Mail', 'students_custom_table'), 'age' => __('Age', 'students_custom_table'), 'ip_address' => __('IP address', 'students_custom_table'), ); return $columns; } function get_sortable_columns() { $sortable_columns = array( 'name' => array('name', true), 'email' => array('email', false), 'age' => array('age', false), 'ip_address' => array('ip_address', false), ); return $sortable_columns; } function get_bulk_actions() { $actions = array( 'delete' => 'Delete' ); return $actions; } function process_bulk_action() { global $wpdb; $table_name = $wpdb->prefix . 'students'; // do not forget about tables prefix if ('delete' === $this->current_action()) { $ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : array(); if (is_array($ids)) $ids = implode(',', $ids); if (!empty($ids)) { $wpdb->query("DELETE FROM $table_name WHERE id IN($ids)"); } } } function prepare_items() { global $wpdb; $table_name = $wpdb->prefix . 'students'; $per_page = 5; $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); $this->_column_headers = array($columns, $hidden, $sortable); $this->process_bulk_action(); $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name"); $paged = isset($_REQUEST['paged']) ? ($per_page * max(0, intval($_REQUEST['paged']) - 1)) : 0; $orderby = (isset($_REQUEST['orderby']) && in_array($_REQUEST['orderby'], array_keys($this->get_sortable_columns()))) ? $_REQUEST['orderby'] : 'name'; $order = (isset($_REQUEST['order']) && in_array($_REQUEST['order'], array('asc', 'desc'))) ? $_REQUEST['order'] : 'asc'; $this->items = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name ORDER BY $orderby $order LIMIT %d OFFSET %d", $per_page, $paged), ARRAY_A); $this->set_pagination_args(array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page) )); } }

コードを注意深く調べると、列「age」と「ip_address」がどのように定義されているかに気付くでしょう。 これで先に進み、最終的に「Students」管理画面の内容を提供する関数を定義することもできます。

 function students_custom_table_page_handler() { global $wpdb; $table = new Students_Custom_Table_List_Table(); $table->prepare_items(); $message = ''; if ('delete' === $table->current_action()) { $message = '<div class="updated below-h2"><p>' . sprintf(__('Items deleted: %d', 'students_custom_table'), count($_REQUEST['id'])) . '</p></div>'; } ?> <div class="wrap"> <div class="icon32 icon32-posts-post"><br></div> <h2><?php _e('Students', 'students_custom_table')?> <a class="add-new-h2" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=students_form');?>"><?php _e('Add new', 'students_custom_table')?></a> </h2> <?php echo $message; ?> <form method="GET"> <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/> <?php $table->display() ?> </form> </div> <?php }

つまり、最初にカスタムのStudents_Custom_Table_List_Tableクラスのインスタンスを作成し、次に学生のテーブル データを含む html 要素を作成しました。 表示されたテーブルを確認できるはずですが、空になることに注意してください。

これで完了です。生徒を追加しましょう。

カスタム データを追加するフォームの作成

前に述べたように、生徒を追加する機能はstudents_custom_table_page_handler_add_form()になります。

 function students_custom_table_page_handler_add_form() { global $wpdb; $table_name = $wpdb->prefix . 'students'; $message = ''; $notice = ''; $default = array( 'id' => 0, 'name' => '', 'email' => '', 'age' => null, 'ip_address' => null, ); if (wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) { $item = shortcode_atts($default, $_REQUEST); $result = $wpdb->insert($table_name, $item); $item['id'] = $wpdb->insert_id; if ($result) { $message = __('Item was successfully saved', 'students_custom_table'); } else { $notice = __('There was an error while saving item', 'students_custom_table'); } } add_meta_box('students_form_meta_box', 'Student data', 'students_custom_table_students_form_meta_box_handler', 'student', 'normal', 'default'); ?> <div class="wrap"> <div class="icon32 icon32-posts-post"><br></div> <h2><?php _e('Student', 'students_custom_table')?> <a class="add-new-h2" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=students');?>"><?php _e('back to list', 'students_custom_table')?></a> </h2> <?php if (!empty($notice)): ?> <div class="error"><p><?php echo $notice ?></p></div> <?php endif;?> <?php if (!empty($message)): ?> <div class="updated"><p><?php echo $message ?></p></div> <?php endif;?> <form method="POST"> <input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/> <input type="hidden" name="id" value="<?php echo $item['id'] ?>"/> <div class="metabox-holder"> <div> <div> <?php do_meta_boxes('student', 'normal', $item); ?> <input type="submit" value="<?php _e('Save', 'students_custom_table')?>" class="button-primary" name="submit"> </div> </div> </div> </form> </div> <?php }

コードでわかるように、最初に新しいレコードに使用される$default配列を設定します。

次に、リクエストが送信され、正しいナンスがあることを確認したら、shortcode_atts() を使用します。 これは非常に便利な組み込みの WordPress 関数で、指定されたパラメーターを組み合わせて、必要に応じてデフォルトを設定します。

最後に、カスタム メタ ボックスを追加してデータをカスタム テーブルに挿入し、プロセスが成功したことを知らせるメッセージを受け取ります。

このチュートリアルでは、実際に使用する場合に追加する必要のあるいくつかの要素を省略しています。 これらには、重複した名前や電子メールが追加された場合に何が起こるかを定義するなどのことを行うことによって、データベースに追加された情報を検証することが含まれます.

最後になりましたが、カスタム メタ ボックスのハンドラーを追加する必要があります。

 function students_custom_table_students_form_meta_box_handler($item) { ?> <table cellspacing="2" cellpadding="5" class="form-table"> <tbody> <tr class="form-field"> <th valign="top" scope="row"> <label for="name"><?php _e('Name', 'students_custom_table')?></label> </th> <td> <input name="name" type="text" value="<?php echo esc_attr($item['name'])?>" size="50" class="code" placeholder="<?php _e('Your name', 'students_custom_table')?>" required> </td> </tr> <tr class="form-field"> <th valign="top" scope="row"> <label for="email"><?php _e('E-Mail', 'students_custom_table')?></label> </th> <td> <input name="email" type="email" value="<?php echo esc_attr($item['email'])?>" size="50" class="code" placeholder="<?php _e('Your E-Mail', 'students_custom_table')?>" required> </td> </tr> <tr class="form-field"> <th valign="top" scope="row"> <label for="age"><?php _e('Age', 'students_custom_table')?></label> </th> <td> <input name="age" type="number" value="<?php echo esc_attr($item['age'])?>" size="50" class="code" placeholder="<?php _e('Your age', 'students_custom_table')?>" required> </td> </tr> <tr class="form-field"> <th valign="top" scope="row"> <label for="ip_address"><?php _e('IP', 'students_custom_table')?></label> </th> <td> <input name="ip_address" type="number" value="<?php echo esc_attr($item['ip_address'])?>" size="50" class="code" placeholder="<?php _e('Your IP address', 'students_custom_table')?>" required> </td> </tr> </tbody> </table> <?php }

以上です。 これで、生徒の追加、生徒のリストの表示、または生徒の削除、データのカスタム データベース テーブルへの保存を可能にするカスタム プラグインができました。