プラグインElementorのelementor/template-library/before_get_source_dataフィルタの使用方法・解説

概要

elementor/template-library/before_get_source_data フィルタは、Elementorのテンプレートライブラリのデータが取得される前に発火します。このフックを使用することで、テンプレートデータのフィルタリングやカスタマイズ、追加データの提供が可能になります。具体的には、以下のような機能を実装する際によく使われます。

  1. テンプレートライブラリのデータソースを変更
  2. ユーザーの役割によるアクセス制御
  3. 特定の条件に基づくテンプレートの除外
  4. カスタムメタデータの追加
  5. テンプレートのカスタム分類の実装
  6. 外部APIからのデータ取得

構文

add_filter( 'elementor/template-library/before_get_source_data', 'your_function_name', 10, 2 );

パラメータ

  • $data: テンプレートライブラリに渡される元データ。
  • $source: データのソースを示す情報(例: ‘Library’、’Custom’など)。

戻り値

フィルタを適用した後、変更されたデータを返します。

使用可能なバージョン

  • Elementor: バージョン3.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_filter( 'elementor/template-library/before_get_source_data', function( $data, $source ) {
    // 特定のソースからのデータを変更
    if ( 'Library' === $source ) {
        $data['custom_field'] = '新しい値';
    }
    return $data;
});

このコードは、テンプレートライブラリが取得するデータにカスタムフィールドを追加しています。特にライブラリから取得する際に適用されます。

サンプル 2: ユーザーの役割によるフィルタリング

add_filter( 'elementor/template-library/before_get_source_data', function( $data, $source ) {
    // 管理者以外のユーザーからのアクセスを制限
    if ( ! current_user_can( 'administrator' ) ) {
        $data['templates'] = array_filter( $data['templates'], function( $template ) {
            return $template['status'] === 'published';
        });
    }
    return $data;
});

この例では、管理者以外のユーザーが取得できるテンプレートを公開済みのものに制限しています。

サンプル 3: テンプレートの除外

add_filter( 'elementor/template-library/before_get_source_data', function( $data, $source ) {
    // 特定のIDを持つテンプレートを除外
    $excluded_ids = [ 1, 2, 3 ]; // 除外するテンプレートID
    $data['templates'] = array_filter( $data['templates'], function( $template ) use ( $excluded_ids ) {
        return ! in_array( $template['id'], $excluded_ids );
    });
    return $data;
});

特定のテンプレートIDを持つテンプレートを除外しています。

サンプル 4: カスタムメタデータの追加

add_filter( 'elementor/template-library/before_get_source_data', function( $data, $source ) {
    // テンプレートにカスタムメタデータを追加
    foreach ( $data['templates'] as &$template ) {
        $template['custom_meta'] = 'カスタムメタ情報';
    }
    return $data;
});

全てのテンプレートにカスタムメタデータを追加しています。

サンプル 5: 外部APIデータを追加

add_filter( 'elementor/template-library/before_get_source_data', function( $data, $source ) {
    // 外部APIからデータを取得し、テンプレートリストに追加
    $response = wp_remote_get( 'https://api.example.com/templates' );
    if ( is_array( $response ) && ! is_wp_error( $response ) ) {
        $additional_templates = json_decode( $response['body'], true );
        $data['templates'] = array_merge( $data['templates'], $additional_templates );
    }
    return $data;
});

外部のAPIからテンプレート情報を取得し、既存のテンプレートリストに追加します。

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


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