LoginSignup
0
0

More than 3 years have passed since last update.

テーマに正しくjsファイル、スタイルシートを読み込ませる方法

Posted at

結論

cssファイルを読み込むにはwp_enqueue_style、
jsファイルを読み込むにはwp_enqueue_scriptを使用する。

functions.php
function test_scripts() {
  wp_enqueue_style( 'main-style', get_template_directory_uri().'/css/main.css' ); // cssファイルを読み込む
  wp_enqueue_script( 'main-script', get_template_directory_uri().'/js/main.js'); // jsファイルを読み込む
}

add_action( 'wp_enqueue_scripts', 'test_scripts' );

使用方法

wp_enqueue_style( $handle, $src, $deps, $ver, $in_footer );
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );

wp_enqueue_style , wp_enqueue_scriptとも関数の規則は同じです。

$handle

スタイルの名前。
ユニークでないければならない。
既存の名前を入れると、キューに追加されない。

$src

スタイルシート、スクリプトファイルまでのURL。
外部ファイルを読み込むことも可能。その場合は絶対パスで入力する。

ちなみに内部ファイルを読み込む際、以下の関数は頻出度が高く、覚えておくこと必須。

get_template_directory_uri(); // 親テーマのディレクトリを取得
get_stylesheet_directory_uri(); // 子テーマのディレクトリを取得
get_stylesheet_uri(); // 子テーマのstyle.cssを取得

詳しくはcodexを見ると良い。
わかりやすく、書かれている。

関数リファレンス/get template directory uri
関数リファレンス/get stylesheet directory uri
関数リファレンス/get stylesheet uri

$deps

このスタイル・スクリプトを読み込む前に、読み込ませたいスタイル・スクリプトの$handleを配列形式で記入する。

$ver

バージョン番号を指定できる。デフォルトはfalseになっている。

$in_footer

デフォルトはfalse。
trueの場合、</body> 終了タグの前に配置。
falseの場合、<head> に置かれる。

終わりに

正直、codexを見れば全て書かれている。
関数リファレンス/wp enqueue style
関数リファレンス/wp enqueue script
しかし、いちいち開くのが億劫だ。高頻出関数の引数くらい覚えておきたいという願いを込めてメモ✍️

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