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

概要

cptui_post_form_action は、Custom Post Type UI プラグインが提供するアクションフックの一つで、カスタム投稿タイプのフォームが送信された際に特定の処理を行うために使用されます。このフックは、特定の情報を処理したり、カスタムのバリデーションやメタデータの保存などを実装する際に役立ちます。以下は、このアクションがよく使用される機能の例です。

  1. フォームデータのカスタムバリデーション
  2. メタデータの追加または更新
  3. 投稿作成後のリダイレクト
  4. 通知の送信(例: メール通知)
  5. 投稿のカスタム設定の適用
  6. カスタムログの保存

構文

do_action('cptui_post_form_action', $post_data);

パラメータ

  • $post_data: フォームから送信された投稿データを含む配列。

戻り値

特に戻り値はありません。フックが正常に実行されると、必要なアクションが実行されます。

使用可能なプラグインバージョン

  • Custom Post Type UI: バージョン 1.10.0以上

使用可能なWordPressバージョン

  • 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_form_action', 'validate_cptui_post_data');

function validate_cptui_post_data($post_data) {
    if (empty($post_data['title'])) {
        // エラーメッセージを表示
        add_settings_error('cptui_errors', 'error', 'タイトルは必須です。');
    }
}

引用元: https://developer.wordpress.org/reference/functions/add_action/

サンプルコード2: メタデータの追加

フォームが送信された際に、追加のメタデータを保存する例です。

add_action('cptui_post_form_action', 'save_additional_meta_data');

function save_additional_meta_data($post_data) {
    if (!empty($post_data['custom_field'])) {
        update_post_meta($post_data['ID'], 'custom_meta_key', sanitize_text_field($post_data['custom_field']));
    }
}

引用元: https://developer.wordpress.org/reference/functions/update_post_meta/

サンプルコード3: 投稿後のリダイレクト

投稿を作成した後に特定のページにリダイレクトする例です。

add_action('cptui_post_form_action', 'redirect_after_post_creation');

function redirect_after_post_creation($post_data) {
    wp_redirect(home_url('/thank-you'));
    exit;
}

引用元: https://developer.wordpress.org/reference/functions/wp_redirect/

サンプルコード4: メール通知の送信

投稿が作成された際に、管理者にメールを送信するサンプルです。

add_action('cptui_post_form_action', 'send_notification_email');

function send_notification_email($post_data) {
    $to = get_option('admin_email');
    $subject = '新しい投稿が作成されました';
    $message = '新しい投稿: ' . $post_data['title'] . 'が作成されました。';
    wp_mail($to, $subject, $message);
}

引用元: https://developer.wordpress.org/reference/functions/wp_mail/

サンプルコード5: カスタムログの保存

フォーム送信内容をカスタムログに記録する例です。

add_action('cptui_post_form_action', 'log_post_submission');

function log_post_submission($post_data) {
    $log_entry = '[' . current_time('mysql') . '] 投稿が作成されました: ' . $post_data['title'] . "n";
    file_put_contents(__DIR__ . '/submission_log.txt', $log_entry, FILE_APPEND);
}

引用元: https://www.php.net/manual/en/function.file-put-contents.php

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


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