09:表示用メインループ設置
公開日:2019年07月13日
更新日:2019年07月19日
表示用メインループ
WordPressはURL内のスラッグ(ページ固有のキーワード)から対象のページを特定してデータベースから情報を取得します。
タイトルや本文などページ内容を表示するには表示用ループを記述します。
スラッグから取得したデータを表示するループをメインループと呼びます。
ループ開始
<?php /***** メインループ開始 *****/ ?> <?php if (have_posts()) :?> <?php while (have_posts()) : the_post(); ?>
ループ終了
<?php endwhile; ?> <?php endif; ?> <?php /***** メインループ終了 *****/ ?>
制御構文
<?php
// スラッグ(URL)をもとにデータベースから条件に応じたページ情報を取得(メインループデータ:暗黙データ)
// メインループデータがページ情報をもっているか確認
if (have_posts()) {
// メインループデータがページ情報をもっている分だけ繰返し処理
while (have_posts()) {
// メインループデータから1件分のページ情報を$post変数にセット
the_post();
// WordPress関数でページ内容を表示
}
}
?>
表示用メインループに置き換え
プロフィールパーツをメインループに置き換えます。
front-page.php
変更前のコード
<div id="profile" class="profile">
<div class="inner">
<h2 class="title">Profile</h2>
<div class="subtitle">人物</div>
<div class="flex">
<div class="flex-item photo">
<img src="<?php echo get_stylesheet_directory_uri(); ?>/img/human.png" alt="YourName">
</div><!-- .flex-item -->
<div class="flex-item text">
<div class="name">YourName</div>
<div class="item-text">
<p>
ウェブに特化したデザイナーです。
SEOを踏まえた正しい文法でコーディングします。お客様にはショップオーナー様、企業のホームページ担当者様、また制作会社様など様々です。
</p>
<p>
ウェブサイトに関することはお気軽にご相談ください。
</p>
</div><!-- .item-text -->
</div><!-- .flex-item -->
</div><!-- .flex -->
</div><!-- .inner -->
</div><!-- .profile -->
変更後コード
<div id="profile" class="profile"> <div class="inner"> <?php /***** メインループ開始 *****/ ?> <?php if (have_posts()) :?> <?php while (have_posts()) : the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> <?php endif; ?> <?php /***** メインループ終了 *****/ ?> </div><!-- .inner --> </div><!-- .profile -->
ページ情報表示用関数
| 関数名 | 内容 |
|---|---|
| the_title() | タイトル表示 |
| the_excerpt() | 抜粋文表示 |
| the_content() | 本文表示 |
| the_time(‘Y年m月d日’) | 投稿日表示 |
| the_permalink() | ページのURLを表示 |
このページで出てくる関数
WordPress関数は「公式サイトのドキュメント」で確認しましょう。
WordPress関数
表示確認
以下URLにアクセスすると以下の表示になります。
http://localhost/WordPressフォルダ名/

※欠席者対応:lesson04 – lesson05
同じタグのコンテンツ
同じカテゴリーのコンテンツ