親カテゴリーindexで子カテゴリー、子カテゴリーで記事タイトルを表示する

2012年12月12日

親カテゴリーindexページで子カテゴリータイトルを、
子カテゴリーindexで記事タイトルを表示する方法を
フォーラムに投稿のあった記事(http://ja.forums.wordpress.org/topic/2393)をもとにカスタマイズしました。

category.phpを作ります。
ソースは以下のとおり。

 

<?php if (have_posts()) : ?>
<?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?>
<h3><?php printf(__('%s', 'kubrick'), single_cat_title('', false)); ?></h3>
<ul>
<?php
if ( is_category() ) :
// クエリからカテゴリーとページ数を取得
$catid = get_query_var( 'cat' );
$paged = get_query_var( 'paged' );
// 子カテゴリーを配列で取得
$children = get_term_children( $catid, 'category' );
// 子カテゴリー一覧の表示件数 (sp = showposts)
$child_sp = -1;
// クエリを発行してしまうと、 single_cat_title() が機能しなくなる
$single_cat_title = single_cat_title( '', false );
// Default テーマの場合次の行のコメントを解除すると幸せ
// $single_cat_title = printf(__('Archive for the '%s' Category', 'kubrick'), $single_cat_title);
// 子カテゴリーが存在する場合、それらを除くクエリを発行
if ( !empty( $children ) ) {
query_posts( array(
'category__in' => array( $catid ),
'category__not_in' => $children,
'paged' => $paged,
) );
}
?>
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<li <?php post_class(); ?> id="post-<?php the_ID(); ?>"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php endif; ?>
<?php
// 子カテゴリーが存在する場合
if ( !empty( $children ) ) :
foreach ( $children as $child ) :
// 子カテゴリーのオブジェクトを取得
$child_cat_object = get_category( $child );
// 孫カテゴリーはスキップ
if ( $child_cat_object->category_parent != $catid ) continue;
// 子カテゴリー用のクエリを作成
query_posts( array(
'cat' => $child,
/*
* 孫カテゴリーを子カテゴリーの記事として含めない場合は 'cat' => $child ではなく
* 'category__in' => array( $child ),
*/
'showposts' => $child_sp,
) );
?>
<?php if ( have_posts() ) :
// 子カテゴリーページのタイトルと URL を取得
$child_cat_title = apply_filters( 'single_cat_title', get_cat_name( $child ) );
$child_cat_link = get_category_link( $child );
?>
<li><a href="<?php echo $child_cat_link; ?>"><?php echo $child_cat_title; ?></a></li>
<?php endif; ?>
<?php
endforeach;
// query_posts を発行している場合にクエリをリセット
wp_reset_query();
endif;
endif;
?>
</ul>
ページトップへ