条件分岐(if文)でCSS&JSを切り替える場合
categoryテンプレートに「category.css」「category.js」を、pageテンプレートに「page.css」「page.js」を読み込む場合、if文での切り替えはこんな感じになると思います。
header.php
<head>
<title>ブログ</title>
<?php if(is_page()): ?>
<link href="<?php bloginfo("template_directory") ?>/css/page.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="<?php bloginfo("template_directory") ?>/js/page.js"></script>
<?php elseif(is_category()): ?>
<link href="<?php bloginfo("template_directory") ?>/css/category.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="<?php bloginfo("template_directory") ?>/js/category.js"></script>
<?php endif; ?>
<?php wp_head(); ?>
</head>
2つくらいだったら全然問題ないですね。
では同じ条件でインクルード元のテンプレートで指定してみます。
インクルード元のテンプレートで指定する場合
「page」「category」テンプレートには「wp_enqueue_style」「wp_enqueue_script」というwpタグを追加します。
これは「wp_head()」の前にする必要があるので「header.php」の前に記述します。
page.php
<?php
wp_enqueue_style("pagecss", get_bloginfo('template_directory').'/css/page.css' );
wp_enqueue_script("pagejs",get_bloginfo("template_directory")."/js/page.js");
?>
<?php get_header(); ?>
<h1>ページ</h1>
<?php get_footer(); ?>
category.php
<?php
wp_enqueue_style("pagecss", get_bloginfo('template_directory').'/css/category.css' );
wp_enqueue_script("pagejs",get_bloginfo("template_directory")."/js/category.js");
?>
<?php get_header(); ?>
<h1>カテゴリー</h1>
<?php get_footer(); ?>
「wp_enqueue_style」「wp_enqueue_script」は第一引数にハンドル名、第二引数にファイルまでのパスを記述します。
同じファイルなら同一のハンドル名にしておくと二重の読み込みを防止することもできます。
header.php
header.phpの条件分岐部分を削除します。
指定したcss&jsは「wp_head()」に入りますので、これは残しておきます。
header.php
<head> <title>ブログ</title> <?php wp_head(); ?> </head>
どうでしょう、ちょっと見やすくなった気がしませんか。