概要
elementor/frontend/before_enqueue_scripts
アクションは、Elementorがフロントエンドでスクリプトやスタイルをエンキューする前に、カスタムスクリプトやスタイルを追加するために使用されます。このフックは、Elementorでのページビルderやテーマのカスタマイズに役立ちます。以下は、このアクションが一般的に利用される機能の例です:
- カスタムCSSやJSファイルの追加
- 特定の条件に基づくスクリプトの条件付き読み込み
- セクションやウィジェットにオリジナルのスタイルを適用
- 新しいショートコードを定義
- 他のプラグインとの競合を避けるための設定
- タイムゾーンやロケーションに基づく動的なスクリプトの読み込み
構文
add_action('elementor/frontend/before_enqueue_scripts', 'your_function_name');
パラメータ
your_function_name
: カスタム関数。スクリプトやスタイルをエンキューするロジックを含む。
戻り値
特に戻り値はありませんが、このアクションはカスタムスクリプトやスタイルのエンキューを実行します。
使用可能なバージョン
- Elementor:バージョン 2.0以上
- WordPress:バージョン 5.0以上
サンプルコード
サンプル1: カスタムCSSを追加
add_action('elementor/frontend/before_enqueue_scripts', function() {
wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/css/custom-style.css');
});
このコードは、Elementorがスクリプトやスタイルをエンキューする前に、カスタムCSSファイルを追加します。
サンプル2: 条件付きスクリプトの読み込み
add_action('elementor/frontend/before_enqueue_scripts', function() {
if (is_page('contact')) {
wp_enqueue_script('contact-form-script', get_template_directory_uri() . '/js/contact-form.js', ['jquery'], null, true);
}
});
このコードは、特定のページ(この場合は「contact」ページ)でのみスクリプトを追加します。
サンプル3: デフォルトのスクリプトを上書き
add_action('elementor/frontend/before_enqueue_scripts', function() {
wp_dequeue_script('elementor-frontend'); // Elementorのデフォルトスクリプトを無効にする
wp_enqueue_script('my-custom-script', get_template_directory_uri() . '/js/my-custom-script.js', [], null, true);
});
このコードは、Elementorのデフォルトスクリプトを無効にし、カスタムスクリプトをエンキューします。
サンプル4: カスタムフォントの追加
add_action('elementor/frontend/before_enqueue_scripts', function() {
wp_enqueue_style('custom-fonts', 'https://fonts.googleapis.com/css?family=Custom+Font');
});
このコードは、Google Fontsからカスタムフォントを追加します。
サンプル5: 動的なデータのエンキュー
add_action('elementor/frontend/before_enqueue_scripts', function() {
wp_localize_script('my-custom-script', 'myAjax', ['ajaxurl' => admin_url('admin-ajax.php')]);
});
このコードは、WordPressのAjax URLをJavaScriptに渡すためのデータを準備します。
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |
この表は、elementor/frontend/before_enqueue_scripts
アクションが他のWordPressフックで使用可能かどうかを示しています。