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

概要

elementor/preview/enqueue_scriptsは、Elementorプラグインのプレビュー表示において、特定のスクリプトやスタイルをエンキュー(登録)するためのアクションフックです。このフックは、Elementorのビジュアルエディタやプレビュー機能を強化する目的でよく使用されます。具体的な使用例は以下の通りです。

  1. カスタムスタイルシートの追加
  2. 特定のJavaScriptライブラリの導入
  3. 管理画面専用のスクリプトの追加
  4. プラグインやテーマの独自機能に必要なスクリプトのエンキュー
  5. 特定のユーザー権限に基づくスクリプトやスタイルの条件付きロード
  6. A/Bテスト用のスクリプトのエンキュー

構文

add_action('elementor/preview/enqueue_scripts', 'your_function_name');

パラメータ

  • 特になし

戻り値

  • 特になし

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

  • Elementor 2.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: カスタムCSSをエンキューする

このコードはElementorプレビューの際にカスタムCSSファイルを追加します。

function custom_enqueue_styles() {
    wp_enqueue_style('custom-style', plugin_dir_url(__FILE__) . 'css/custom-style.css');
}
add_action('elementor/preview/enqueue_scripts', 'custom_enqueue_styles');

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

サンプルコード2: 特定のJavaScriptライブラリをロードする

このコードは、Elementorのプレビューに特定のJavaScriptライブラリを追加します。

function add_custom_js() {
    wp_enqueue_script('custom-js', plugin_dir_url(__FILE__) . 'js/custom.js', array('jquery'), null, true);
}
add_action('elementor/preview/enqueue_scripts', 'add_custom_js');

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

サンプルコード3: 特定の条件下でスクリプトをエンキューする

このコードは、管理者ユーザーにのみ特定のスクリプトをエンキューします。

function conditional_enqueue() {
    if (current_user_can('administrator')) {
        wp_enqueue_script('admin-specific-script', plugin_dir_url(__FILE__) . 'js/admin-script.js', array(), null, true);
    }
}
add_action('elementor/preview/enqueue_scripts', 'conditional_enqueue');

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

サンプルコード4: A/Bテスト用のスクリプトをエンキューする

このコードでは、A/Bテストの際に特定のスクリプトをエンキューする機能を実装します。

function ab_test_enqueue_script() {
    if (isset($_GET['test'])) {
        wp_enqueue_script('ab-test-script', plugin_dir_url(__FILE__) . 'js/ab-test.js', array(), null, true);
    }
}
add_action('elementor/preview/enqueue_scripts', 'ab_test_enqueue_script');

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

サンプルコード5: プラグインの依存関係を追加する

このコードは、Elementorのプレビューエディタにプラグインの依存関係をエンキューします。

function enqueue_plugin_dependencies() {
    wp_enqueue_script('plugin-dependency', 'https://example.com.js', array('jquery'), null, true);
}
add_action('elementor/preview/enqueue_scripts', 'enqueue_plugin_dependencies');

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

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


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