プラグインAdvanced custom fields(ACF)のacf/pre_save_postアクションの使用方法・解説

概要

acf/pre_save_post アクションは、ACF(Advanced Custom Fields)を使用してフォームデータを保存する際に実行されるフックです。このアクションは、acf_form_head 関数の実行中にデータを保存するために使用される $post_id をカスタマイズします。これにより、カスタムデータの保存や特定の条件に基づいた処理を行うことができます。

よく使われる機能

acf/pre_save_post アクションは以下のような機能を実装する際によく使われます。
1. ポストの種類を変更する
2. 既存のデータをベースに新しいデータを作成する
3. フォームデータのバリデーションを実施する
4. セキュリティトークンの確認を行う
5. メタデータの追加・更新を行う
6. フォーム送信時のカスタムリダイレクト処理を行う

構文

add_action('acf/pre_save_post', 'my_acf_pre_save_post', 20);

パラメータ

  • $post_id: 保存されるポストのID

戻り値

  • int または false: 保存プロセス中に変更されたポストID。

使用可能なバージョン

  • ACFバージョン: 5.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('acf/pre_save_post', 'change_post_type');
function change_post_type($post_id) {
    if ($post_id === 'options') {
        // ポストタイプを変更
        return 'custom_post_type';
    }
    return $post_id;
}

引用元: https://www.advancedcustomfields.com/resources/pre_save_post/

サンプル2: データのバリデーション

このコードは、特定のフィールドが空でないかを確認します。

add_action('acf/pre_save_post', 'validate_acf_form_data');
function validate_acf_form_data($post_id) {
    if (empty($_POST['acf']['field_name'])) {
        // エラーメッセージを表示
        acf_add_error('field_name', 'このフィールドは必須です。');
        return false; // 保存しない
    }
    return $post_id;
}

引用元: https://www.advancedcustomfields.com/resources/pre_save_post/

サンプル3: メタデータの追加

フォームデータを保存する際に、追加のメタデータを追加します。

add_action('acf/pre_save_post', 'add_custom_meta_data');
function add_custom_meta_data($post_id) {
    // メタデータを追加
    update_post_meta($post_id, 'custom_meta_key', 'custom_value');
    return $post_id;
}

引用元: https://www.advancedcustomfields.com/resources/pre_save_post/

サンプル4: リダイレクト処理

データが正常に保存された後にリダイレクトします。

add_action('acf/pre_save_post', 'redirect_after_save');
function redirect_after_save($post_id) {
    if (is_admin()) {
        return;
    }
    if ($some_condition) {
        wp_redirect(home_url('/thank-you'));
        exit;
    }
    return $post_id;
}

引用元: https://www.advancedcustomfields.com/resources/pre_save_post/

サンプル5: セキュリティトークンの検証

CSRF攻撃を防ぐためにセキュリティトークンを検証します。

add_action('acf/pre_save_post', 'verify_nonce');
function verify_nonce($post_id) {
    if (!isset($_POST['my_nonce_field']) || !wp_verify_nonce($_POST['my_nonce_field'], 'my_nonce_action')) {
        return false; // 保存しない
    }
    return $post_id;
}

引用元: https://www.advancedcustomfields.com/resources/pre_save_post/

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


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