Wp Databaseのロゴ

Wp Database

コミュニティ
mralaminahamed
wp-database

Use when a WordPress plugin needs a custom database table — creating with dbDelta (strict SQL format: two spaces before PRIMARY KEY, no trailing comma), writing versioned upgrade routines with version_compare and register_activation_hook, querying with $wpdb prepared statements (prepare, insert, update, delete, get_row, get_results, get_var), debugging with $wpdb->last_error or SAVEQUERIES, schema migrations between plugin versions, uninstall cleanup, multisite table handling with switch_to_blog / get_sites, or seeding test/preview data into custom tables. Triggers: "create a custom table", "dbDelta not working", "dbDelta not creating my table", "write a migration", "wpdb query", "wpdb prepare", "slow query on my custom table", "upgrade my database schema", "add a column to my table", "seed test data", "how do I store this in a custom table", "database upgrade routine", "table not being created on activation", "prepare placeholder wrong", "last_error is empty after query", "SAVEQUERIES debug", "version_compare for db upgrade", "register_activation_hook table", "wpdb prefix table name", "uninstall drops table", "multisite per-site table", "charset_collate missing". Not for: WordPress options API or post meta — use those when a custom table is not needed.

概要

公開者mralaminahamed
リポジトリwp-dev-skills
スキル名wp-database
スター
29
フォーク
3
同梱ファイル
4
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 4個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    mralaminahamedがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Wp Database」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/mralaminahamed/wp-dev-skills/tree/trunk/skills/wp-database
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/mralaminahamed/wp-dev-skills.git /tmp/wp-dev-skills
mkdir -p .claude/skills
cp -r /tmp/wp-dev-skills/skills/wp-database .claude/skills/wp-database
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでWp Databaseを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にWp Databaseを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Wp Databaseは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

WordPress Custom Database Tables

Model note: dbDelta schema and CRUD patterns are mechanical (haiku). Query optimisation and multi-version data migrations require cross-file reasoning — use sonnet for those sub-tasks.

Create and manage custom database tables in WordPress plugins: dbDelta() for schema definition, versioned upgrade routines, $wpdb CRUD with prepared statements, and data migration strategies.

When to use

  • "Create a custom DB table for my plugin", "set up plugin schema with dbDelta".
  • "Write a migration for plugin upgrade", "run schema changes on update".
  • "Query a custom table", "insert/update/delete with $wpdb".
  • "Optimise a slow custom query", "add an index to a plugin table".
  • "Migrate data from post meta to a custom table".

Not for: WooCommerce order table operations — use wp-woocommerce. General $wpdb query optimisation in core WP tables — use wp-performance (official skill).

Method

1. Create table with dbDelta

dbDelta() is the only WP-safe way to create and alter tables — it diffs the current schema against the SQL and applies only the necessary changes.

php
function my_plugin_create_tables() {
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate(); // e.g. DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci

    // $wpdb->prefix respects multisite site prefix automatically
    $table_log  = $wpdb->prefix . 'my_plugin_log';
    $table_meta = $wpdb->prefix . 'my_plugin_item_meta';

    // IMPORTANT: two spaces before PRIMARY KEY, one space before each KEY
    // IMPORTANT: no trailing comma on last field before closing paren
    $sql = "CREATE TABLE {$table_log} (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  item_id bigint(20) unsigned NOT NULL,
  action varchar(100) NOT NULL DEFAULT '',
  message longtext NOT NULL,
  user_id bigint(20) unsigned NOT NULL DEFAULT 0,
  created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY  (id),
  KEY item_id (item_id),
  KEY created_at (created_at)
) {$charset_collate};

CREATE TABLE {$table_meta} (
  meta_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  item_id bigint(20) unsigned NOT NULL,
  meta_key varchar(255) NOT NULL DEFAULT '',
  meta_value longtext,
  PRIMARY KEY  (meta_id),
  KEY item_id (item_id),
  KEY meta_key (meta_key(191))
) {$charset_collate};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
}

Critical dbDelta formatting rules (violations cause silent failures):

  • Two spaces after PRIMARY KEY (e.g. PRIMARY KEY (id))
  • Field definitions must end with a comma except the last field before the closing paren
  • KEY lines go after all field definitions, before the closing paren
  • Only CREATE TABLE statements — no ALTER TABLE (dbDelta handles column additions, not removals)
  • Always include {$charset_collate} at the end

2. Versioned upgrade routine

Track schema version in an option; only re-run dbDelta when the version changes:

php
define( 'MY_PLUGIN_DB_VERSION', '1.3.0' );

function my_plugin_maybe_upgrade_db() {
    $installed = get_option( 'my_plugin_db_version', '0' );
    if ( version_compare( $installed, MY_PLUGIN_DB_VERSION, '>=' ) ) {
        return; // already up to date
    }

    my_plugin_create_tables(); // always safe to re-run dbDelta

    // Version-specific data migrations
    if ( version_compare( $installed, '1.2.0', '<' ) ) {
        my_plugin_migrate_to_1_2_0();
    }
    if ( version_compare( $installed, '1.3.0', '<' ) ) {
        my_plugin_migrate_to_1_3_0();
    }

    update_option( 'my_plugin_db_version', MY_PLUGIN_DB_VERSION );
}
add_action( 'plugins_loaded', 'my_plugin_maybe_upgrade_db' );

Run on plugins_loaded (every request until updated), not just on activation — catches updates after auto-update or version switch.

3. $wpdb CRUD

Always use $wpdb->prepare() for any value from user input or untrusted source.

Insert:

php
$result = $wpdb->insert(
    $wpdb->prefix . 'my_plugin_log',
    [
        'item_id'    => $item_id,
        'action'     => 'view',
        'message'    => $message,
        'user_id'    => get_current_user_id(),
        'created_at' => current_time( 'mysql' ),
    ],
    [ '%d', '%s', '%s', '%d', '%s' ] // format for each value: %d int, %s string, %f float
);
$inserted_id = $wpdb->insert_id;

Update:

php
$wpdb->update(
    $wpdb->prefix . 'my_plugin_log',
    [ 'message' => $new_message ],          // data
    [ 'id'      => $log_id ],               // where
    [ '%s' ],                               // data format
    [ '%d' ]                                // where format
);

Delete:

php
$wpdb->delete(
    $wpdb->prefix . 'my_plugin_log',
    [ 'item_id' => $item_id ],
    [ '%d' ]
);

Select — single row:

php
$row = $wpdb->get_row(
    $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}my_plugin_log WHERE id = %d",
        $log_id
    )
); // returns stdClass or null

Select — multiple rows:

php
$rows = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}my_plugin_log WHERE item_id = %d ORDER BY created_at DESC LIMIT %d",
        $item_id,
        50
    )
); // returns array of stdClass

Select — single value:

php
$count = (int) $wpdb->get_var(
    $wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->prefix}my_plugin_log WHERE action = %s",
        'view'
    )
);

Raw query (DDL / no-result):

php
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->prefix}my_plugin_log WHERE created_at < %s",
        gmdate( 'Y-m-d H:i:s', strtotime( '-30 days' ) )
    )
);

4. Error handling

php
$result = $wpdb->insert( ... );
if ( false === $result ) {
    // $wpdb->last_error contains the MySQL error
    error_log( 'my-plugin DB error: ' . $wpdb->last_error );
    return new WP_Error( 'db_insert_error', $wpdb->last_error );
}

Enable query logging during development:

php
define( 'SAVEQUERIES', true );
// Then: print_r( $wpdb->queries )

5. Schema migrations (data migrations)

For migrating existing data (not just schema changes):

php
function my_plugin_migrate_to_1_2_0() {
    global $wpdb;

    // Example: move post meta to custom table
    $meta_rows = $wpdb->get_results(
        "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_my_plugin_data'"
    );

    if ( ! $meta_rows ) return;

    $table = $wpdb->prefix . 'my_plugin_log';
    foreach ( $meta_rows as $row ) {
        $wpdb->insert( $table, [
            'item_id' => $row->post_id,
            'message' => $row->meta_value,
            'action'  => 'migrated',
        ], [ '%d', '%s', '%s' ] );
    }

    // Remove the old meta after successful migration
    $wpdb->delete( $wpdb->postmeta, [ 'meta_key' => '_my_plugin_data' ], [ '%s' ] );
}

For large datasets, use batches (via wp-background-processing):

php
function my_plugin_migrate_batch( $offset = 0 ) {
    global $wpdb;
    $batch = $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = '_old_key' LIMIT 100 OFFSET %d",
        $offset
    ) );
    // ... process batch ...
    if ( count( $batch ) === 100 ) {
        // More to process — schedule next batch
        as_enqueue_async_action( 'my_plugin_migrate_batch', [ 'offset' => $offset + 100 ], 'my-plugin' );
    } else {
        update_option( 'my_plugin_migration_complete', true );
    }
}

6. Table removal on uninstall

Use register_uninstall_hook (not deactivation_hook) for destructive cleanup:

php
// uninstall.php (registered via register_uninstall_hook(__FILE__, ...) or placed at plugin root)
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) exit;

global $wpdb;

// Drop per-site tables on multisite
if ( is_multisite() ) {
    $sites = get_sites( [ 'number' => 0, 'fields' => 'ids' ] );
    foreach ( $sites as $site_id ) {
        switch_to_blog( $site_id );
        $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}my_plugin_log" );
        delete_option( 'my_plugin_db_version' );
        restore_current_blog();
    }
} else {
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}my_plugin_log" );
    delete_option( 'my_plugin_db_version' );
}

7. Seeding sample / preview data (dev only)

To populate custom tables with realistic data for local preview, write a standalone script run via WP-CLI's wp eval-file — never auto-loaded by the plugin. Keep it in a tools/ dir and document it in tools/README.md.

php
<?php
// tools/seed-dev-data.php — run: wp eval-file tools/seed-dev-data.php [--fresh]
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) { exit( "Run via: wp eval-file <this file>\n" ); }
global $wpdb;
$table = $wpdb->prefix . 'my_plugin_log';

// --fresh truncates first. TRUNCATE is destructive — gate it, and expect the
// agent permission classifier to block it unless tables are already empty.
if ( in_array( '--fresh', (array) ( $args ?? [] ), true ) ) {
    $wpdb->query( "TRUNCATE TABLE {$table}" ); // phpcs:ignore
}

foreach ( $rows as $row ) {
    $wpdb->insert( $table, $row ); // hardcoded columns only
}
WP_CLI::success( 'Seeded.' );

Conventions that keep seeders safe and re-runnable:

  • Idempotent where it matters. A seeder that creates linked records (WP users, EDD payments) should skip rows already linked — e.g. if ( ! empty( $row->payment_id ) ) continue; — so reruns don't duplicate. A pure log-filler can be additive; say so in the script header and accept a count arg ((int) ( $args[0] ?? 0 ) ?: 20).
  • Link to real WP objects, not fakes. Create real users with wp_insert_user() and reuse by email (get_user_by); mint EDD orders through the plugin's own purchase wrapper (e.g. an EDD integration class) rather than raw inserts, so the seeded data exercises the real code path. Write the resulting user_id / payment_id back onto the custom-table row.
  • Generate via WP-CLI, verify via wp db query. Confirm row counts/links after seeding.
  • Dev-only. Never ship tools/; never run against production. Use current_time('mysql') / gmdate() for timestamps, and seed extra/JSON columns with wp_json_encode().

Note on randomness: scripts run by wp eval-file may warn on large int math ($x * 2654435761 overflows to float) — keep PRNG seeds inside & 0x7fffffff.

Common Mistakes

MistakeFix
Wrapper methods that discard $wpdb->insert() return value cause silent failuresAlways check the return value and propagate $wpdb->last_error upstream — callers cannot diagnose a failure the wrapper swallowed. Return null/WP_Error on failure, never silently return as if the insert succeeded

Notes

  • dbDelta() can ADD columns but cannot remove them. Removing columns requires ALTER TABLE DROP COLUMN in a manual migration step.
  • Never use $wpdb->prepare() with %s for integers — always %d. Using %s on an integer is not a security issue but causes type coercion surprises.
  • Column names in $wpdb->insert() / update() / delete() are NOT escaped — they must be hardcoded, never user-supplied.
  • Cache expensive custom queries: $results = wp_cache_get( $cache_key, 'my_plugin' ); if ( false === $results ) { $results = $wpdb->get_results(...); wp_cache_set( $cache_key, $results, 'my_plugin', 300 ); }
  • Always include bigint(20) unsigned NOT NULL AUTO_INCREMENT as the primary key — matches WP core table conventions.
  • Use gmdate() not date() for DB timestamps; WP's current_time('mysql') returns local time — use it only when you need WP's configured timezone.

References

  • references/dbdelta-rules.md — dbDelta() rules: strict SQL formatting requirements, column change limitations, and safe schema diff patterns
  • references/migration-strategies.md — Versioned upgrade routines: db_version pattern, migration function registration, and idempotent migration checklist
  • references/wpdb-patterns.md — $wpdb prepared statement patterns, insert/update/delete helpers, and custom-table query conventions

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Wp Database」では何ができますか?

Use when a WordPress plugin needs a custom database table — creating with dbDelta (strict SQL format: two spaces before PRIMARY KEY, no trailing comma), writing versioned upgrade routines with version_compare and register_activation_hook, querying with $wpdb prepared statements (prepare, insert, update, delete, get_row, get_results, get_var), debugging with $wpdb->last_error or SAVEQUERIES, schema migrations between plugin versions, uninstall cleanup, multisite table handling with switch_to_blog / get_sites, or seeding test/preview data into custom tables. Triggers: "create a custom table",...

TypingMindでWp Databaseを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Wp Databaseはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにWp Databaseをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/mralaminahamed/wp-dev-skills/tree/trunk/skills/wp-databaseを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Wp Databaseを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Wp Databaseで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもWp Databaseを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Wp Database」は無料ですか?

はい。mralaminahamedがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇