シゴトノコバコ

投稿ページ(single.php)で記事の情報を表示する基本のコードです。

この書き方は WordPress のメインループと呼ばれ、URL に対応した投稿データを自動で取得して表示します。

コード

<?php if ( have_posts() ) : ?>
  <?php while ( have_posts() ) : the_post(); ?>
    <article>
      <time datetime="<?php echo esc_attr( get_the_date( 'Y-m-d' ) ); ?>">
        <?php echo esc_html( get_the_date( 'Y.m.d' ) ); ?>
      </time>
      <h1><?php the_title(); ?></h1>
      <?php the_content(); ?>
    </article>
  <?php endwhile; ?>
<?php endif; ?>

よく使うテンプレートタグ

タグ 出力内容
the_title() 記事タイトル
the_content() 本文
get_the_date() 投稿日を取得
the_permalink() 記事の URL
the_post_thumbnail() アイキャッチ画像

注意点

  • the_title() を title 属性などの属性値に使う場合は、the_title_attribute() を使います。
  • the_content() は、ブロック、ショートコード、埋め込み、自動整形などの本文用フィルターを通して出力します。通常の投稿本文は the_content() を使います。
  • get_the_content() は the_content() の単純な代替ではありません。本文を独自に加工する場合は、ブロックやショートコードをどう扱うかを決め、出力先に合わせてエスケープします。

補足

このメインループは page.php や archive.php でも同じ書き方で使えます。

トップページで最新記事一覧を出したい場合など、URL と無関係な投稿を取得するときは WP_Query を使ったサブクエリが必要です。


関連記事