CSSファイルの管理をfunctions.php
で一元化。
まだ、header.php
のheadに直接書き込んでる方は是非こちらの方法を覚えて下さい。
functions.phpの設定
スタイルシートの登録
<?php wp_register_style( $handle, $src, $deps, $ver, $media ); ?>
引数 | 初期値 | 説明 |
$handle | (なし) | 必須 / 識別名 |
$src | (なし) | 必須 / CSSのパス |
$deps | array() | CSSの依存性 / このCSSより前に読み込まれる必要があるCSSのハンドルを配列指定。 ない場合、空の配列を指定。 |
$ver | false | falseの場合、?ver=5.2.2のようにWPのバージョンが付与されます。 1.2のようにすると、?ver=1.2が付与されます。 nullにすると表示されません |
$media | all | media属性 |
スタイルシートの読み込み
<?php wp_enqueue_style( $handle, $src, $deps, $ver, $media ); ?>
wp_register_styleと異なる点
$srcは必須ではなく、オプションとなります。wp_register_style()
で登録されている場合、そのハンドルを使って追加できます。
実例
よくあるパターンをサンプルとして説明。
function wpqw_register_style() {
wp_register_style( 'reset', get_template_directory_uri() . '/css/reset.min.css' );
wp_register_style( 'style', get_stylesheet_uri() );
wp_register_style( 'home', get_template_directory_uri() . '/css/home.css' );
wp_register_style( 'comment', get_template_directory_uri() . '/css/comment.min.css' );
wp_register_style( 'awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', array(), null, 'all' );
wp_register_style( 'overwrite', get_template_directory_uri() . '/css/overwrite.css', array( 'reset', 'style', 'home', 'comment' ) );
wp_register_style( 'print', get_template_directory_uri() . '/css/print.css', array(), null, 'print' );
}
function wpqw_add_stylesheet() {
wpqw_register_style();
wp_enqueue_style( 'reset' );
wp_enqueue_style( 'style' );
wp_enqueue_style( 'awesome' );
if ( is_front_page() ) {
wp_enqueue_style( 'home' );
} elseif ( is_singular() ) {
wp_enqueue_style( 'comment' );
}
wp_enqueue_style( 'overwrite' );
wp_enqueue_style( 'print' );
}
add_action( 'wp_print_styles', 'wpqw_add_stylesheet' );
1〜9行目のwp_register_style()
でCSSファイルを登録しています。
3行目、テーマフォルダ直下のCSSファイルは、get_stylesheet_uri()
で取得できます。
その他のファイルは、get_template_directory_uri()
でテーマフォルダまでのパスを取得します。
7行目は、あとからCSSを上書きする時のために、array()
でハンドルを配列で指定し、最後に読み込むようになります。
12行目からの、wp_enqueue_style()
で事前に登録したハンドル名を使って呼び出します。
15行目〜のように、条件分岐が使えるので、コメント機能など他のページで使われないクラスを専用にまとめておく事で、表示速度の向上が望めます。
6行目のようなCDNでの読み込みは推奨されていません。
印刷用スタイル
印刷用CSSがある場合、8行目のように、$mediaをprintとする事で、media属性を設定できます。
その場合、$depsや$verが初期値のままだとしても省略する事ができません。
wp_register_style( 'print', get_template_directory_uri() . '/css/print.css', array(), null, 'print' );