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

概要

elementor/common/after_register_scriptsアクションは、Elementorが提供するフックの一つで、Elementorのスクリプトが登録された後に呼び出されます。このフックは、Elementorのページビルダーにおいて、カスタムのスクリプトやスタイルを追加する時によく利用されます。具体的には以下のような機能を実装する際に使用されることが一般的です:

  1. カスタムJavaScriptファイルの追加
  2. 特定の条件に応じたCSSファイルの読み込み
  3. Elementorのウィジェットに対するスクリプトの制御
  4. 他のプラグインとの互換性を持たせるカスタムスクリプトの統合
  5. スクリプトの依存関係の管理
  6. パフォーマンス向上のためのスクリプトの最適化

構文

add_action( 'elementor/common/after_register_scripts', 'your_custom_function' );

パラメータ

このアクションには特にパラメータは存在しません。主にメソッドを実装するために使用します。

戻り値

このアクションも特に戻り値を返すものではなく、ただし、登録されたアクション内で別の処理を実行することで別の戻り値を得ることが可能です。

Elementorのバージョン

このアクションはElementorのバージョン3.0以上で使用可能です。

WordPressのバージョン

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: カスタムスクリプトの追加

このコードは、Elementorの特定のページに対してカスタムJavaScriptを追加します。

add_action( 'elementor/common/after_register_scripts', function() {
    wp_enqueue_script( 'custom-elementor-script', get_stylesheet_directory_uri() . '/js/custom-script.js', [ 'jquery' ], '1.0', true );
} );

引用元: WordPress Codex

サンプルコード2: 条件付きCSSの追加

Elementorの特定のウィジェットでのみスタイルを追加する例です。

add_action( 'elementor/common/after_register_scripts', function() {
    if ( is_page( 'my-custom-page' ) ) {
        wp_enqueue_style( 'custom-elementor-style', get_stylesheet_directory_uri() . '/css/custom-style.css' );
    }
} );

引用元: Elementor Developer Documentation

サンプルコード3: スクリプトの依存関係を設定

他のスクリプトに依存するカスタムスクリプトを登録する例です。

add_action( 'elementor/common/after_register_scripts', function() {
    wp_enqueue_script( 'dependent-script', get_template_directory_uri() . '/js/dependent.js', [ 'jquery', 'elementor-frontend' ], null, true );
} );

引用元: Stack Overflow

サンプルコード4: 特定のウィジェット用スクリプトの追加

特定のElementorウィジェットに対してスクリプトを追加する例です。

add_action( 'elementor/common/after_register_scripts', function() {
    if ( ElementorPlugin::instance()->widgets_manager->get_widget_types() ) {
        wp_enqueue_script( 'widget-specific-script', get_template_directory_uri() . '/js/widget-script.js', [], null, true );
    }
} );

引用元: Elementor GitHub

サンプルコード5: 非公式スクリプトの統合

非公式のプラグインとの互換性を持たせるためのスクリプトを追加する例です。

add_action( 'elementor/common/after_register_scripts', function() {
    wp_enqueue_script( 'non-official-plugin-compat', 'https://example.com/js/non-official-plugin.js', [ 'jquery' ], null, true );
} );

引用元: Dev.to

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


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