2026年5月20日

2026年5月20日

WordPressプラグインでユーザーメタを管理する方法

はじめに

WordPressのUser Meta APIは update_user_meta() / get_user_meta() でユーザーごとの追加情報をデータベースに保存できます。プロフィール欄の拡張・ユーザー設定・ポイント管理など幅広い用途に使えます。

症状・原因

  • ユーザーのプロフィールに独自フィールドを追加したい
  • ユーザーごとの設定値や数値(ポイント・購入回数等)を保存したい
  • WP-CLIでユーザーメタを確認・更新したい
  • ユーザーメタで絞り込んだユーザー一覧を取得したい

解決手順

ステップ1:User Meta APIの基本操作

// メタを追加(同じキーが既にある場合は追加しない)
add_user_meta($user_id, '_myplugin_points', 0, true);  // unique=true

// メタを取得
$points = get_user_meta($user_id, '_myplugin_points', true);  // single=true で単一値
$all    = get_user_meta($user_id, '_myplugin_log', false);     // single=false で配列

// メタを更新(なければ追加)
update_user_meta($user_id, '_myplugin_points', 100);

// メタを削除
delete_user_meta($user_id, '_myplugin_points');

// 現在のログインユーザーのメタを取得
$current_user_id = get_current_user_id();
$points = (int) get_user_meta($current_user_id, '_myplugin_points', true);

ステップ2:プロフィール欄にカスタムフィールドを追加する

// プロフィール編集画面にフィールドを追加
add_action('show_user_profile', 'myplugin_add_profile_fields');
add_action('edit_user_profile', 'myplugin_add_profile_fields');

function myplugin_add_profile_fields(\WP_User $user): void {
    $phone = get_user_meta($user->ID, '_myplugin_phone', true);
    $company = get_user_meta($user->ID, '_myplugin_company', true);
    ?>
    <h3>追加情報</h3>
    <table class="form-table">
        <tr>
            <th><label for="myplugin_phone">電話番号</label></th>
            <td>
                <input type="tel"
                       id="myplugin_phone"
                       name="myplugin_phone"
                       value="<?php echo esc_attr($phone); ?>"
                       class="regular-text">
            </td>
        </tr>
        <tr>
            <th><label for="myplugin_company">会社名</label></th>
            <td>
                <input type="text"
                       id="myplugin_company"
                       name="myplugin_company"
                       value="<?php echo esc_attr($company); ?>"
                       class="regular-text">
            </td>
        </tr>
    </table>
    <?php
}

// プロフィール保存時にメタを更新
add_action('personal_options_update', 'myplugin_save_profile_fields');
add_action('edit_user_profile_update', 'myplugin_save_profile_fields');

function myplugin_save_profile_fields(int $user_id): void {
    if (!current_user_can('edit_user', $user_id)) {
        return;
    }
    update_user_meta(
        $user_id,
        '_myplugin_phone',
        sanitize_text_field($_POST['myplugin_phone'] ?? '')
    );
    update_user_meta(
        $user_id,
        '_myplugin_company',
        sanitize_text_field($_POST['myplugin_company'] ?? '')
    );
}

ステップ3:ユーザーメタで絞り込んだユーザーを取得する

// ポイントが100以上のユーザーを取得
$users = get_users([
    'meta_key'     => '_myplugin_points',
    'meta_value'   => 100,
    'meta_compare' => '>=',
    'meta_type'    => 'NUMERIC',
    'orderby'      => 'meta_value_num',
    'order'        => 'DESC',
    'number'       => 20,
]);

foreach ($users as $user) {
    $points = (int) get_user_meta($user->ID, '_myplugin_points', true);
    echo $user->display_name . ': ' . $points . 'ポイント' . PHP_EOL;
}

// 特定メタが設定されていないユーザーを取得
$users_without_phone = get_users([
    'meta_query' => [
        [
            'key'     => '_myplugin_phone',
            'compare' => 'NOT EXISTS',
        ],
    ],
]);

ステップ4:WP-CLIでユーザーメタを管理する

# ユーザーのメタ一覧を確認
wp user meta list {USER_ID} --format=table

# 特定メタの値を取得
wp user meta get {USER_ID} _myplugin_points

# メタを更新
wp user meta update {USER_ID} _myplugin_points 500

# メタを削除
wp user meta delete {USER_ID} _myplugin_points

# 特定メタを持つユーザーを検索
wp user list --meta_key=_myplugin_points --meta_value=100 --format=table

# ユーザー一覧をメタ値つきで表示
wp user list --fields=ID,user_login,display_name --format=table

ステップ5:ユーザーメタを一括操作する

# 全ユーザーにメタを初期設定(初回マイグレーション)
wp eval "
foreach (get_users(['fields' => 'ID']) as \$uid) {
    if (!get_user_meta(\$uid, '_myplugin_points', true)) {
        update_user_meta(\$uid, '_myplugin_points', 0);
    }
}
echo count(get_users()) . ' users processed';
"

# 特定メタの値を持つユーザー数を確認
wp eval "
global \$wpdb;
echo \$wpdb->get_var(\"SELECT COUNT(*) FROM {\$wpdb->usermeta}
  WHERE meta_key = '_myplugin_points' AND meta_value > 0\");
"

注意事項

  • ユーザーメタキーはプラグインプレフィックス(_myplugin_)を付けて他プラグインとの衝突を防いでください
  • get_user_meta($id, $key, true) で取得した値は常に文字列です。数値として使う場合は (int) でキャストしてください
  • プロフィール保存時は必ず current_user_can('edit_user', $user_id) で権限確認してください

まとめ

User Meta APIは update_user_meta() / get_user_meta() でユーザーごとのデータを管理できます。プロフィール画面への追加は show_user_profile / edit_user_profile フックで実装し、wp user meta list でWP-CLIから確認できます。

お気軽にご相談ください

お見積りへ お問い合わせへ