プラグインElementorのelementor/document/before_saveアクションの使用方法・解説

概要

elementor/document/before_save アクションは、Elementor ドキュメントが保存される前にカスタム処理を実行するためのフックです。このアクションは、Elementor でカスタムな機能を構築する際によく使われるため、特に多くの場面で活用されます。以下はこのアクションがよく使用される機能の一部です:

  1. データのバリデーション – 保存前にデータが正しいか確認する。
  2. メタデータの追加 – ドキュメントに対して追加情報を付加する。
  3. カスタム計算 – ドキュメントの保存時に特定の計算を行う。
  4. カスタムフィールドの処理 – Elementor のドキュメントにカスタムフィールドを追加または更新する。
  5. 変更履歴の管理 – 保存される前に変更を追跡する。
  6. 外部APIとの連携 – 保存時に外部のサービスとデータを送受信する。

構文

add_action( 'elementor/document/before_save', 'your_custom_function', 10, 2 );

パラメータ

  • $document – Elementor ドキュメントオブジェクト。
  • $data – 保存されるデータの配列。

戻り値

このアクションは特別な戻り値を持ちませんが、カスタム処理によって文書が保存されるときの動作を変更することができます。

使用可能なバージョン

  • Elementor: 2.0以上
  • WordPress: 5.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( 'elementor/document/before_save', function( $document, $data ) {
    if ( empty( $data['settings']['custom_field'] ) ) {
        throw new Exception( 'Custom field is required.' );
    }
}, 10, 2 );

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

このサンプルコードは、文書の保存時に特定のメタデータを追加します。

add_action( 'elementor/document/before_save', function( $document, $data ) {
    $document->update_meta( '_my_custom_meta', 'Some value' );
}, 10, 2 );

サンプルコード3: カスタム計算

このサンプルコードは、保存時に特定のデータに基づいてカスタム計算を行い、その結果を保存します。

add_action( 'elementor/document/before_save', function( $document, $data ) {
    $total = 0;
    foreach ( $data['settings']['values'] as $value ) {
        $total += $value;
    }
    $document->update_meta( '_total_value', $total );
}, 10, 2 );

サンプルコード4: カスタムフィールドの処理

このサンプルコードは、保存前にカスタムフィールドに特定の形式の値をセットします。

add_action( 'elementor/document/before_save', function( $document, $data ) {
    $data['settings']['formatted_field'] = 'Formatted: ' . $data['settings']['raw_field'];
}, 10, 2 );

サンプルコード5: 外部APIとの連携

このサンプルコードは、保存前に外部APIにデータを送信します。

add_action( 'elementor/document/before_save', function( $document, $data ) {
    wp_remote_post( 'https://example.com/api', [
        'body' => json_encode( $data['settings'] ),
        'headers' => [ 'Content-Type' => 'application/json' ],
    ] );
}, 10, 2 );

引用元のページは特にありませんが、サンプルコードやその使用方法についてはWordPressやElementorの公式ドキュメントを参照することをお勧めします。

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


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