TwentyTwelveでカテゴリページの表示に関わるファイルをまとめてみました。個別記事の表示についてまとめたページと似たような形式で書いています。
カテゴリページの表示で主役を担うはずのcategory.php
表示に関わるファイルを把握するためには、まず、テンプレート階層 – WordPress Codex 日本語版の5.5 カテゴリー表示を見ておきましょう。
それによると、カテゴリページの表示に使われるファイルは以下の優先順位で決定されます。
- category-slug.php
- category-ID.php
- category.php
- archive.php
- index.php
TwentyTwelveのテンプレートファイルを見てみると次のようになっています。
- category-slug.phpは無い
- category-ID.phpも無い
- category.phpはある
というわけで、カテゴリページ表示の主役はcategory.phpが担うはずです。
実は、category.phpにインクルードされているテンプレートファイルが主役
ところが、そのcategory.phpは、他のテンプレートファイルをインクルードしまくりです。
<?php
/**
* The template for displaying Category pages.
*
* Used to display archive-type pages for posts in a category.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Twenty_Twelve
* @since Twenty Twelve 1.0
*/
get_header(); ?>
<section id="primary" class="site-content">
<div id="content" role="main">
<?php if ( have_posts() ) : ?>
<header class="archive-header">
<h1 class="archive-title"><?php printf( __( 'Category Archives: %s', 'twentytwelve' ), '<span>' . single_cat_title( '', false ) . '</span>' ); ?></h1>
<?php if ( category_description() ) : // Show an optional category description ?>
<div class="archive-meta"><?php echo category_description(); ?></div>
<?php endif; ?>
</header><!-- .archive-header -->
<?php
/* Start the Loop */
while ( have_posts() ) : the_post();
/* Include the post format-specific template for the content. If you want to
* this in a child theme then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
endwhile;
twentytwelve_content_nav( 'nav-below' );
?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</div><!-- #content -->
</section><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
以下のインクルードが行われていることがわかります。
- get_header();でheader.phpをインクルード
- カテゴリーに属する記事が有る場合(<?php if ( have_posts() ) : ?>~<?php else : ?>)、get_template_part( ‘content’, get_post_format() );でcontent.phpをインクルード
- カテゴリーに属する記事がない場合(<?php else : ?>~<?php endif; ?>)、get_template_part( ‘content’, ‘none’ );でcontent-none.phpをインクルード
- get_sidebar();でsidebar.phpをインクルード
- get_footer();でfooter.phpをインクルード
このように、category.phpは個別投稿ページの表示を引き受けながら、大半の仕事を他のテンプレートファイルに丸投げして、それをインクルードによって取り込んでいるのです。
category.phpが自ら表示の仕事を行っているのは、以下の2箇所だけです。
- <header class=”archive-header”>~</header><!– .archive-header –>
- twentytwelve_content_nav( ‘nav-below’ );
レイアウト構造と役割分担
以上のような事実を踏まえて、以前に書いたカテゴリページのレイアウト構造を表す図に手を加え、カテゴリに属する投稿がある場合において、どのファイルがどの部分の表示を担当してるかをざっくりと図示してみました。
このように、カテゴリページのカスタマイズはcategory.phpだけを見ていればいいというものではないです。
むしろ、header.php、content.php、content-none.php、sidebar.php、footer.phpをしっかり見ないといけません。
上の図を利用すると、カテゴリページのカスタマイズが多少とも楽になるのではないかと思います。