Created
June 6, 2016 10:44
-
-
Save DriftwoodJP/4dd00361eac89b60f10932bf37533261 to your computer and use it in GitHub Desktop.
wp_enqueue_scripts をフックし、スクリプトとスタイルをキューに入れる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* WordPress でスクリプトとスタイルをキューに入れる | |
* | |
* @link http://notnil-creative.com/blog/archives/1299 | |
* @return boolean wp_enqueue_scripts をフックし my_scripts を有効化。常に true。 | |
*/ | |
function my_scripts() { | |
// 管理画面では読み込まない | |
if ( ! is_admin() ) { | |
// スタイルシートディレクトリーを取得する。この方法だと子テーマでもそのまま使える | |
$dir = get_stylesheet_directory_uri(); | |
// テーマのjsディレクトリーのmy-script.jsをキューに入れる。 | |
// さらに、jQueryに依存するのでjQueryの後で入れるように指定した場合。 | |
wp_enqueue_script( 'my-script', $dir.'/js/my-script.js', array( 'jquery' ) ); | |
// jQueryをGoogleがホストするものに差し替える | |
wp_deregister_script( 'jquery' ); | |
wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js' ); | |
// Google Maps APIを読み込む | |
// 豆: 第3引数にNULLを入れると末尾に余計な ?ver=xxx が付かない | |
wp_enqueue_script( 'google-maps-api', '//maps.google.com/maps/api/js?sensor=false', array(), null ); | |
// テーマのjsディレクトリーのmy-map.jsをキューに入れる。 | |
// jQueryとGoogle Maps APIの両方に依存するので、配列で両方を指定した場合。 | |
wp_enqueue_script( 'my-map', $dir.'/js/my-map.js', array( 'jquery', 'google-maps-api' ) ); | |
// head タグ内ではなく閉じ body 直前にスクリプトを出したい場合は、第4引数にtrue | |
wp_enqueue_script( 'my-footer', $dir.'/js/my-footer.js', array(), false, true ); | |
// 特定のページでスクリプトを出したい場合 | |
if ( is_front_page() ) { | |
wp_enqueue_script( 'my-top', $dir.'/js/my-top.js' ); | |
} | |
// 不要なスクリプトをキューから外す(親テーマやプラグインで要らないのがあったとき等) | |
wp_dequeue_script( 'parent-script' ); | |
// スタイルシートも基本同じように使えます。 | |
wp_enqueue_style( 'my-css', $dir.'/css/my-css.css' ); | |
// 不要なスタイルをキューから外す(親テーマやプラグインで要らないのがあったとき等) | |
wp_dequeue_style( 'parent-style' ); | |
} | |
} | |
add_action( 'wp_enqueue_scripts', 'my_scripts', 50 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment