概要
elementor/db/before_save
アクションフックは、Elementorで作成されたページやテンプレートがデータベースに保存される直前に実行されるフックです。このフックを利用することで、保存処理の直前にカスタムロジックを追加することができます。例えば、データの検証やフィールドの編集、カスタムオプションの追加などに使用されることがあります。
よく使われる用途としては以下のようなものがあります:
- データのバリデーション処理
- 保存するデータの変更やフィルタリング
- カスタムメタデータの追加
- 外部APIとの連携
- ログの記録やトラッキング
- コンテンツの最適化(SEO対策など)
構文
add_action( 'elementor/db/before_save', 'your_callback_function' );
パラメータ
$post_data
: 保存されるデータの配列。
戻り値
このアクションフック自体は値を返しませんが、$post_data
の内容を変更することで、保存されるデータに影響を与えます。
使用可能なプラグインElementorのバージョン
- 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/db/before_save', 'validate_elementor_data' );
function validate_elementor_data( $post_data ) {
if ( empty( $post_data['title'] ) ) {
wp_die( 'タイトルは必須です。' );
}
}
このサンプルコードは、Elementorで作成されたページのタイトルが空でないかを確認し、空の場合にはエラーメッセージを表示して保存を中止します。
サンプル2: カスタムメタデータの追加
add_action( 'elementor/db/before_save', 'add_custom_meta_data' );
function add_custom_meta_data( $post_data ) {
$post_data['custom_meta'] = 'カスタムデータ';
}
このコードは、Elementorの保存処理の際にカスタムメタデータを追加します。$post_data
の配列に新しいエントリーを挿入します。
サンプル3: 外部APIとの連携
add_action( 'elementor/db/before_save', 'sync_with_external_api' );
function sync_with_external_api( $post_data ) {
$response = wp_remote_post( 'https://api.example.com/sync', [
'body' => $post_data,
]);
}
このサンプルでは、Elementorで保存されるデータを外部APIに送信して同期します。APIのエンドポイントにPOSTリクエストを送信します。
サンプル4: 特定のクラス名をチェック
add_action( 'elementor/db/before_save', 'check_css_class' );
function check_css_class( $post_data ) {
if ( strpos( $post_data['css_classes'], 'custom-class' ) !== false ) {
$post_data['content'] .= '<!-- Custom class found -->';
}
}
このサンプルコードは、特定のCSSクラスが存在するかを確認し、存在する場合にはコンテンツにコメントを追加します。
サンプル5: データの変更
add_action( 'elementor/db/before_save', 'modify_elementor_content' );
function modify_elementor_content( $post_data ) {
$post_data['content'] = str_replace( 'old-text', 'new-text', $post_data['content'] );
}
このコードは、Elementorで保存される内容の中で特定のテキストを新しいテキストに置き換えます。保存前にこの変更が適用されます。