HTML→WordPress - ループ文とページャー

投稿記事をループ文にする

  • index.phpの編集
  • メインのテンプレートファイルの編集

the_title … 記事のタイトルを表示
get_the_date … 記事の日付を表示
the_category … 記事のカテゴリーを表示
comments_number … コメント数を表示
the_content … コンテンツ(画像含む)
the_permalink … 記事のパーマリンクを出力(URLのこと)、続きを読むのリンクを表示

HTML上で記述した内容
<article class="post">
<h2><a href="#">記事タイトル</a></h2>
<p class="post-meta">
  <span class="post-date">2018年9月23日</span>
  <span class="category">Category - <a href="#">ケーキ</a></span>
  <span class="comment-num"><a href="#">Comment : 0</a></span>
</p><!-- /.post-meta -->
<p>・・・ 記事の本文(画像も含む) ・・・</p>
<p class="more-link"><a href="#">続きを読む &raquo;</a></p>
</article><!-- /.post -->
WordPressのループ
  1. 記事があるかどうかのチェック
  2. 記事があったら繰り返し処理開始
  3. WordPressループ終了
<main class="main">


<?php if(have_posts()): while(have_posts()): the_post(); ?>

<article <?php post_class(); ?>>

<h2><?php the_title(); ?></h2>

<p class="post-meta">
  <span class="post-date"><?php echo get_the_date(); ?></span>
  <span class="category">カテゴリー : <a href="#"><?php the_category(', '); ?></a></span>
  <span class="comment-num"><a href="#">コメント : <?php comments_number('0','1','2'); ?></a></span>
</p><!-- /.post-meta -->

<?php the_content(); ?>

<p class="more-link"><a href="<?php the_permalink(); ?>">続きを読む &raquo;</a></p>

</article><!-- /.post -->

<?php endwhile; endif; ?>


</main><!-- /.main -->
投稿記事情報(日付・カテゴリー・コメント数)
<p class="post-meta">
  <span class="post-date"><?php echo get_the_date(); ?></span>
  <span class="category">カテゴリー : <a href="#"><?php the_category(', '); ?></a></span>
  <span class="comment-num"><a href="#">コメント : <?php comments_number('0','1','2'); ?></a></span>
</p><!-- /.post-meta -->

ページャー

  • 前後の記事に移動する機能
<?php if($wp_query->max_num_pages>1): ?>
<div class="pager">
  <span class="alignleft"><?php next_posts_link('&laquo; 古い記事'); ?></span>
  <span class="alignright"><?php previous_posts_link('新しい記事 &raquo;'); ?></span>
</div><!-- /.pager -->
<?php endif; ?>

まとめ

  • index.phpの編集をまとめる
記事を投稿

<?php get_header(); ?>

<div class="container">
<main class="main">

<?php if(have_posts()): while(have_posts()): the_post(); ?>
<article <?php post_class(); ?>>
<h2><?php the_title(); ?></h2>
<p class="post-meta">
  <span class="post-date"><?php echo get_the_date(); ?></span>
  <span class="category">カテゴリー : <a href="#"><?php the_category(', '); ?></a></span>
  <span class="comment-num"><a href="#">コメント : <?php comments_number('0','1','2'); ?></a></span>
</p><!-- /.post-meta -->
<?php the_content(); ?>
<p class="more-link"><a href="<?php the_permalink(); ?>">続きを読む &raquo;</a></p>

</article><!-- /.post -->
<?php endwhile; endif; ?>

<?php if($wp_query->max_num_pages>1): ?>
<div class="pager">
  <span class="alignleft"><?php next_posts_link('&laquo; 古い記事'); ?></span>
  <span class="alignright"><?php previous_posts_link('新しい記事 &raquo;'); ?></span>
</div><!-- /.pager -->
<?php endif; ?>

</main><!-- /.main -->

<?php get_sidebar(); ?>

<?php get_footer(); ?>