Last active
January 24, 2020 05:11
-
-
Save lunaluna/5c02c8bcfb2cb52a24d618a5efa12d71 to your computer and use it in GitHub Desktop.
【WordPress】wp_add_inline_script( string $handle, string $data, string $position = 'after' )
This file contains 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 4.4.x までの書き方 | |
function ex_enqueue_scripts() { | |
if ( !wp_script_is( 'jquery', 'done' ) ) { | |
wp_enqueue_script( 'jquery' ); | |
} | |
} | |
add_action( 'wp_enqueue_scripts', 'ex_enqueue_scripts' ); | |
function ex_head() { | |
?> | |
<script> | |
jQuery(function($){ | |
$("span").append("Hello world!"); | |
}); | |
</script> | |
<?php | |
} | |
add_action( 'wp_head', 'ex_head', 10000 ); |
This file contains 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 4.5.x 以降の書き方 | |
function inline_enqueue_scripts() { | |
if( !wp_script_is( 'jquery', 'done' ) ) { | |
wp_enqueue_script( 'jquery' ); | |
} | |
$script = ' | |
jQuery(function($){ | |
$("span").append("Hello world!"); | |
});'; | |
wp_add_inline_script( 'jquery-migrate', $script, 'after' ); | |
} | |
add_action( 'wp_enqueue_scripts', 'inline_enqueue_scripts' ); | |
/* | |
- enqueue_scripts の中で呼び出す | |
- $handle : 関連する JavaScript (ファイル)のハンドル名 | |
- $data : 追加したい JavaScript のコード | |
- $position : 指定したハンドル名の JavaScript (ファイル)読込の前に出力する(‘before’)か、後ろに出力する(‘after’)かを指定(デフォルトは’after’) | |
- $handle で呼び出す JavaScript (ファイル)の enqueue よりもあとに記述しないと $handle が認識されず呼びだせない | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WordPress ちょっとしたスクリプトを記述する簡単な方法
WordPress4.5から使える wp_add_inline_script を使ってJetpackの「SnowStorm」を桜に変えて降らせてみる
wp_add_inline_script( string $handle, string $data, string $position = 'after' )