データベース操作
複雑なデータを扱うプラグインでは、投稿メタデータだけでなく、独自のカスタムテーブルを作成した方が効率的な場合があります。基本的な操作方法を解説します。
カスタムテーブルの作成
<?php
function my_plugin_create_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'my_plugin_logs';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
user_id bigint(20) NOT NULL,
action varchar(100) NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta($sql);
}
register_activation_hook(__FILE__, 'my_plugin_create_table');
dbDelta関数の特徴
dbDelta()は、テーブルが既に存在する場合は差分だけを反映してくれる安全な関数です。プラグインの有効化時(register_activation_hook)に呼び出すのが基本パターンです。基本的なCRUD操作
<?php
global $wpdb;
$table = $wpdb->prefix . 'my_plugin_logs';
// 追加
$wpdb->insert($table, array('user_id' => 1, 'action' => 'login'));
// 取得
$logs = $wpdb->get_results("SELECT * FROM $table ORDER BY created_at DESC LIMIT 10");
// 更新
$wpdb->update($table, array('action' => 'logout'), array('id' => 5));
// 削除
$wpdb->delete($table, array('id' => 5));
アンインストール時のテーブル削除
プラグイン削除時にカスタムテーブルも削除したい場合は、uninstall.phpファイルに削除処理を記述します。
<?php
// uninstall.php
if (!defined('WP_UNINSTALL_PLUGIN')) exit;
global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}my_plugin_logs");