概要
wp_enqueue_script アクションは、WordPressのテーマやプラグインにスクリプトファイルを追加するための手段を提供します。このアクションを使用すると、スクリプトを出力用のキューに入れることができ、複数のスクリプトを効率的に管理することができます。主に以下のような機能を実装する際によく使われます。
- テーマやプラグインによるJavaScriptの追加
- jQueryや他のライブラリの登録と管理
- スクリプトの依存関係の解決
- スクリプトのバージョン管理
- グローバル変数の設定
- スクリプトの位置(ヘッダーまたはフッター)の指定
- 環境に応じたスクリプトの条件付き読み込み
- カスタムスクリプトの統合
構文
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
パラメータ
$handle(string): スクリプトの識別子$src(string): スクリプトのURL$deps(array): 依存するスクリプトの識別子の配列$ver(string | boolean): スクリプトのバージョン番号$in_footer(boolean): フッターに出力するかどうかの指定
戻り値
無
関連する関数
使用可能なバージョン
WordPress 2.1 以降
コアファイルのパス
wp-includes/script-loader.php
この関数のアクションでの使用可能性
| アクション名 | 使用例 |
|---|---|
| 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: jQueryの追加
function my_scripts() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'my_scripts');
説明: WordPressに含まれるjQueryライブラリを追加するサンプルです。
サンプル2: カスタムスクリプトの追加
function add_custom_script() {
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'add_custom_script');
説明: テーマのカスタムJavaScriptファイルを追加し、jQueryに依存させる例です。
サンプル3: スクリプトのバージョン管理
function load_script_with_version() {
wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/script.js', array(), '1.2.3', true);
}
add_action('wp_enqueue_scripts', 'load_script_with_version');
説明: スクリプトのバージョンを指定することでキャッシュの管理を行うサンプルです。
サンプル4: スクリプトの依存関係を設定
function enqueue_dependent_scripts() {
wp_enqueue_script('first-script', get_template_directory_uri() . '/js/first.js', array(), null, true);
wp_enqueue_script('second-script', get_template_directory_uri() . '/js/second.js', array('first-script'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_dependent_scripts');
説明: 1つ目のスクリプトに依存する2つ目のスクリプトを追加する例です。
サンプル5: フッターにスクリプトを追加
function enqueue_footer_scripts() {
wp_enqueue_script('footer-script', get_template_directory_uri() . '/js/footer.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_footer_scripts');
説明: スクリプトをHTMLのフッター部分に追加するためのサンプルです。