Twenty Twelveを使用して下の画像のようにカテゴリー別に投稿記事を表示するカスタマイズについてのコード例を書きます。
以前、同じ内容の記事を書いたのですが、若干修正しています。
また、get_posts()を使用した方法については後で書きます。

下のコードが、カテゴリー別に記事の一覧を表示するコードになります。
<?php
$categories = get_categories(array('parent'=>0));
foreach($categories as $category) :
?>
<header class="entry-header">
<h1 class="entry-title"><a href="<?php the_permalink($category->cat_name); ?>"> <?php echo $category->cat_name; ?></a></h1>
</header>
<ul class="entry-content-front">
<?php query_posts('numberposts=5&cat='.$category->cat_ID);?>
<?php while ( have_posts() ) : the_post(); ?>
<li class="entry-title-front"><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr__( sprintf( __('Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
このコードは、get_categories()で表示するカテゴリー情報を取得して、h1タグの中にあるcategory->cat_nameでカテゴリー名を表示しています。
また、get_categories()の引数に与えるパラメータはいくつかありますが、親カテゴリーと子カテゴリーがあるサイトで最上位(親)カテゴリーだけ表示するので、(’parent’=>0)にしています。
query_postsのパラメータには、numberpostsでカテゴリー別に表示数する記事の数(lここでは5記事)を設定、catにカテゴリーIDを設定してます。
このコードの後に何か表示するコードがあると、最後の投稿データを保持しているので、よろしくないということで、wp_reset_query()でリセットしています。
style.css
上記のコードを使用した場合、上の画像の表示のCSSが下のコードになります。
.entry-header {
margin-bottom: 12px;
margin-bottom: 0.8571428571rem;
}
.entry-header .entry-title {
border-bottom: 1px solid rgb(204,204,204);
}
ul.entry-content-front {
line-height: 1.846153846;
font-size: 18px;
margin-bottom: 36px;
list-style: disc inside;
}
スポンサーリンク


コメント