LoginSignup
0
0

WordPressでJavaScriptを埋め込む方法(再掲)

Last updated at Posted at 2024-05-22

はじめに

今回はWordPressでモーダルを実装する際にJavaScriptをどこに埋め込めばいいか悩んだのでその解決策をまとめる。

問題点

WordPressでJavaScriptのコードをどのphpファイルに埋め込めばいいのか。

解決策①

footer.phpの</body>の直前に埋め込むことで解決する。
ただしこれは非推奨な方法な模様。

footer.php
	<?php wp_footer() ?>
	<script>
         //ここにJavaScriptの処理
	</script>
</body>
</html>

解決策②

もう一つの方法がheader.phpのheadタグ内の<?php wp_head(); ?>より上に外部ファイルを読み込む関数を記述するというもの。

header.php
	<script src="<?php echo get_template_directory_uri(); ?>{jsファイルのパス}"></script>

	<?php wp_head(); ?>
<?php echo get_template_directory_uri(); ?> 

上記の関数は、テーマフォルダ内のパスを取得するための関数である。

解決策③

この方法がWordPressによって推奨されている。

functions.phpに以下のように記述する。

function.php
function my_method() {
	wp_enqueue_script(
		'js_script',
		get_template_directory_uri() . '/myscript.js',
	);
}
add_action('wp_enqueue_scripts', 'my_method');

wp_enqueue_script関数の第一引数には固有のハンドル名(ファイルを区別するための名前)を記述し、第二引数にはスクリプトのパスを指定する。第二引数にはパスを取得できるget_template_directory_uri()を使用。

参考:https://developer.wordpress.org/reference/functions/wp_enqueue_script/

以上の方法でWordPressにJavaScriptを読み込むことができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0