プラグインCustom Post Type UIのcptui_post_type_update_saveアクションの使用方法・解説

概要

cptui_post_type_update_saveは、Custom Post Type UIプラグインのフックであり、新しいカスタム投稿タイプを更新または保存した際に呼び出されます。このアクションは、ユーザーがカスタム投稿タイプを作成または編集する際に特定の処理を行うために非常に便利です。以下のような機能を実装する際によく使われます。

  1. カスタム投稿タイプのメタデータを保存する。
  2. カスタムタクソノミーの設定を行う。
  3. 投稿タイプに基づいたカスタムフィールドを初期設定する。
  4. 外部APIを使って投稿内容を同期する。
  5. カスタム投稿タイプのビューをカスタマイズするためのフックを追加する。
  6. 管理画面での通知やメッセージを表示する。

構文

add_action('cptui_post_type_update_save', 'my_custom_post_type_update', 10, 2);

パラメータ

  • $post_type (string): 更新されたカスタム投稿タイプの名前。
  • $meta (array): 投稿タイプのメタデータや設定が含まれる連想配列。

戻り値

このアクションは特に戻り値を持たず、主にサイドエフェクト(副作用)を持つ処理のために使用されます。

利用可能なバージョン

  • Custom Post Type UIのバージョン: 1.9.0以上
  • WordPressのバージョン: 4.0以上

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプル1: メタデータを保存

add_action('cptui_post_type_update_save', 'save_custom_meta_data', 10, 2);
function save_custom_meta_data($post_type, $meta) {
    if ($post_type === 'my_custom_type') {
        update_option('my_custom_meta', $meta);
    }
}

このサンプルコードは、my_custom_typeというカスタム投稿タイプが更新された時に、そのメタデータをWordPressオプションテーブルに保存します。

サンプル2: タクソノミーの設定

add_action('cptui_post_type_update_save', 'set_custom_taxonomy', 10, 2);
function set_custom_taxonomy($post_type, $meta) {
    if ($post_type === 'my_custom_type') {
        register_taxonomy_for_object_type('my_taxonomy', $post_type);
    }
}

このサンプルコードは、カスタム投稿タイプmy_custom_typeが更新された際、その投稿タイプにカスタムタクソノミーを関連付けます。

サンプル3: カスタムフィールドの初期設定

add_action('cptui_post_type_update_save', 'initialize_custom_fields', 10, 2);
function initialize_custom_fields($post_type, $meta) {
    if ($post_type === 'my_custom_type') {
        add_post_meta($post_id, 'custom_field_key', 'default_value', true);
    }
}

このサンプルコードは、新しく作成されたカスタム投稿タイプmy_custom_typeに対して、カスタムフィールドを初期化します。

サンプル4: 通知メッセージの表示

add_action('cptui_post_type_update_save', 'display_update_message', 10, 2);
function display_update_message($post_type, $meta) {
    if ($post_type === 'my_custom_type') {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible"><p>カスタム投稿タイプが正常に更新されました。</p></div>';
        });
    }
}

このサンプルコードは、my_custom_typeが更新された後に、管理画面に成功メッセージを表示します。

サンプル5: 外部APIとの同期

add_action('cptui_post_type_update_save', 'sync_with_external_api', 10, 2);
function sync_with_external_api($post_type, $meta) {
    if ($post_type === 'my_custom_type') {
        wp_remote_post('https://externalapi.example.com/sync', [
            'body' => json_encode($meta),
            'headers' => ['Content-Type' => 'application/json'],
        ]);
    }
}

このサンプルコードは、my_custom_typeが更新された際に外部APIに対してメタデータを送信しています。

この関数について質問する


上の計算式の答えを入力してください