第6回目のWordPressのサイト作り
前回の記事までの記事はこちらから
WordPress オリジナルテーマを作る〜ヘッダー〜
WordPress オリジナルテーマを作る〜ヘッダーその2〜
WordPress オリジナルテーマを作る〜メイン部分〜
WordPress オリジナルテーマを作る〜メイン部分その2〜
WordPress オリジナルテーマを作る〜サイドとフッター〜
WordPress オリジナルテーマを作る〜テーマに分割~
記事の一覧を作成する
つぎはブログのトップ画面になるindex.phpに記事の一覧を表示させる方法を見ていきます。
記事の一覧を取得するにはループ処理を使います。
ループ処理は以下のような流れで書きます。
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> //ループする部分 <?php end while; else: ?> //記事がなかった場合の処理 <?php endif; ?>
これを前に作ったindex.phpに当てはめるとこうなります。
<!-- index.php --> <?php get_header(); ?> <div class="container"> <div class="main"> <div class="post"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php if (has_post_thumbnail()) : ?> <?php the_post_thumbnail() :?> <?php else: ?> <img src="<?php echo get_template_directory_uri(); ?>/img/no-img.png"> <? php endif; ?> <div class="post-content"> <p class="ttl"><a href="<?php the_permalink(); ?>"></a><?php the_title(); ?></p> <div class="post-meta"> <ul> <li><i class="fa fa-clock-o" aria-hidden="true"></i><?php echo get_the_date_date(); ?></li> <li><i class="fa fa-folder-open-o" aria-hidden="true"></i><? php the_category(', '); ?></li> </ul> </div> <div class="post-txt"> <p><?php the_excerpt(); ?></p> </div> </div> </div> <?php end while; else: ?> <p>記事はありません</p> <?php endif; ?> </div> <?php get_sidebar(); ?> </div> <?php get_footer(); ?>
今回使ったテンプレートタグは
the_title();
→タイトルを取得する
echo get_the_date_date();
→投稿日を取得する
the_category(‘, ‘);
→カテゴリーを取得する
複数ある場合はカンマ区切りで記載する
the_excerpt();
→本文を抜粋して取得する
the_post_thumbnail();
→サムネイルを取得する
echo get_template_directory_uri();
→テンプレートのディレクトリーのurlを取得する
です。
サムネイルの取得に関しては
サムネイルが設定されているかどうかをまず調べて
設定されていたらそれを表示、
設定されていなかったらno-imageの画像を表示という風に設定します。
<?php if (has_post_thumbnail()) : ?> //サムネイルが設定されているかどうかを調べる <?php the_post_thumbnail() :?> //サムネイルがある場合はそれを表示 <?php else: ?> //サムネイルがない場合 <img src="<?php echo get_template_directory_uri(); ?>/img/no-img.png"> <? php endif; ?>
こんな感じです。
これで記事の一覧が取得できました!
今日はここまでにしたいと思います。
せば!