Last active
August 29, 2015 14:07
-
-
Save RyoSugimoto/f8b6cd5f9d790b11c9f2 to your computer and use it in GitHub Desktop.
WorsPressでJavaScriptやCSSを読み込む方法のまとめ。「functions.php」で一元管理する。
(http://notnil-creative.com/blog/archives/1299)
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
/** | |
* スクリプトとスタイルをキューに入れる | |
*/ | |
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', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ); | |
// Google Maps APIを読み込む | |
// 豆: 第3引数にNULLを入れると末尾に余計な ?ver=xxx が付かない | |
wp_enqueue_script( 'google-maps-api', 'http://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