カテゴリー別に投稿記事とアイキャッチ画像を表示するコードを作成しました(Twenty Twelveを利用)。
下の画像が、表示されるイメージになります。
カテゴリー名を表示して、そのカテゴリーに属する投稿記事のアイキャッチ画像と記事タイトルと抜粋記事を表示するコードになります。

Twenty Twelveで作成していますが、他のテーマで使用する場合、articleタグの中の一部だけ変更(しなくても大丈夫)するだけで使用できます。
カテゴリーは、親と子のカテゴリーがあるのを前提に作成しています。
コードの使用場所は、index.phpやpage.phpファイルのdiv.contentの間にあるコードを削除して下のコードを挿入します。
<?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>
<div class="entry-content-front">
<?php query_posts('numberposts=5&cat='.$category->cat_ID);?>
<?php while ( have_posts() ) : the_post(); ?>
<article class="front-post">
<?php the_post_thumbnail('small'); ?>
<div 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></div>
<?php the_excerpt(); ?>
</article>
<?php endwhile; ?>
</div>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
下のコードは、get_posts()で作成した同じ表示をするコードです。
<?php
global $post;
$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>
<div class="entry-content-front">
<?php $mypost = get_posts( 'numberposts=5&cat='.$category->cat_ID );?>
<?php foreach( $mypost as $post ) : setup_postdata($post); ?>
<article class="front-post">
<?php the_post_thumbnail('small'); ?>
<div 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></div>
<?php the_excerpt(); ?>
</article>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
上のコードサンプルでは、thumbnail(‘small’)としているので、アイキャッチ画像のサイズを設定するためにfunctions.phpファイルに下のコードを追加します。
もし、下のコードを追加する場合、アップロードしてる画像があるときは、画像の再生成が必要になります。
add_image_size( 'small', 100, 100, true);
上のコードに対応するスタイルシートのサンプルを作成しました。
好みに合わせ編集して使用してください。
.entry-header {
margin-bottom: 12px;
margin-bottom: 0.8571428571rem;
}
.entry-header .entry-title {
border-bottom: 4px double #ccc;
line-height: 1.846153846;
}
.entry-content-front {
margin-bottom: 36px;
}
.entry-content-front .attachment-small {
float: left;
margin-right: 10px;
}
.entry-title-front {
margin-bottom: 10px;
display: block;
font-size: 18px;
}
article.front-post {
overflow:hidden;
margin-bottom: 12px;
border-bottom: 1px solid #ccc;
}
スポンサーリンク


コメント