記事一覧
次はいよいよ記事の部分です。
最初に用意したサンプルは、一つの記事を表示させる構造になっていましたが、記事一覧を表示させる様にしてみます。
登録されてる記事の分だけ、「<div class="post"> … </div><!-- /post -->」を繰り返すループを記述します。
「<div class="post">」の前に「<?php if(have_posts()) : while (have_posts()) :」と書き、投稿があった場合、投稿分だけ表示をさせます。
その後に、記事を表示させるための命令で「the_post();」と書きます。
index.php
<?php
if (have_posts()) :
while (have_posts()) :
the_post();
?>
<div class="post">
投稿がなかった場合
「</div><!-- /post -->」の後に「<?php endwhile; else: ?>」として、その後に記事がなかった場合のメッセージを書きます。
その後に「<?php endif; ?>」で if を閉じれば OK です。
index.php
</div><!-– /post -–> <?php endwhile; else: ?> <p>記事はありません!</p> <?php endif; ?>
これで、記事がある間は「<div class="post"> … </div><!-- /post -->」が表示されます。
記事の各部分の置き換え
記事の中身をテンプレートタグで置き換えていきます。
記事ヘッダに記事タイトル、メタ情報(投稿日、カテゴリ)を表示します。
記事タイトルは「<?php the_title(); ?>」とします。
個別記事へのリンクは「<?php the_permalink(); ?>」とします。
日付部分は「<?php echo get_the_date(); ?>」とします。
カテゴリー部分は、「<?php the_category(‘, ‘); ?>」とします。
これだけでカテゴリーが複数あってもカンマ区切りで、リンク付きで表示してくれます。
一覧ページでは本文を表示するよりも抜粋を表示したいので、「<?php the_excerpt(); ?>」というタグを使います。
index.php
<div class="post">
<div class="post-header">
<h2>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<div class="post-meta">
<?php echo get_the_date(); ?> 【<?php the_category(', '); ?>】
</div>
</div>
<div class="post-content">
<div class="post-list">
<?php the_excerpt(); ?>
</div
</div>
</div><!-- /post -->
ページナビゲーション
次にナビゲーション部分を作ります。
「<div class="prev">前へ</div>」の中身を「<?php previous_posts_link(); ?>」に、「<div class="next">次へ</div>」の中身を「<?php next_posts_link(); ?>」に書き換えればOKです。
index.php
<div class="navigation"> <div class="prev"><?php previous_posts_link(); ?></div> <div class="next"><?php next_posts_link(); ?></div> </div>
「previous_posts_link()」 ,「next_posts_link()」はループの外で使う必要があります。
以上で記事一覧を表示させることができるようになりました。
最終的にindex.phpは以下の様になります。
index.php
<?php get_header(); ?>
<div id="main" class="container">
<div id="posts">
<?php
if (have_posts()) :
while (have_posts()) :
the_post();
?>
<div class="post">
<div class="post-header">
<h2>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<div class="post-meta">
<?php echo get_the_date(); ?> 【<?php the_category(', '); ?>】
</div>
</div>
<div class="post-content">
<div class="post-list">
<?php the_excerpt(); ?>
</div>
</div>
</div><!-- /post -->
<?php
endwhile;
else:
?>
<p>記事はありません!</p>
<?php
endif;
?>
<div class="navigation">
<div class="prev"><?php previous_posts_link(); ?></div>
<div class="next"><?php next_posts_link(); ?></div>
</div>
</div><!-- /posts -->
<?php get_sidebar();?>
</div><!-- /main -->
<?php get_footer(); ?>
</body>
</html>

