the_date()

関数の概要

the_date()は、WordPressで現在の投稿やページの公開日を表示するための関数です。この関数は、ループ内で使用され、投稿の公開日を動的に表示するのに便利です。デフォルトでは、日付はフォーマット設定に従って表示されます。

パラメータの説明

the_date()関数は4つのオプションパラメータを受け取ります。

  1. $d (string, オプション): 日付のフォーマット。指定しない場合、サイト全体のデフォルトフォーマットが使用されます。
  2. $before (string, オプション): 日付の前に表示する文字列。
  3. $after (string, オプション): 日付の後に表示する文字列。
  4. $echo (bool, オプション): trueの場合、日付を表示します。falseの場合、日付を返します。デフォルトはtrueです。

使用例

以下は、the_date()関数を使用して投稿の公開日を表示する例です。

<?php
// 投稿のループ内で公開日を表示する
if (have_posts()) {
    while (have_posts()) {
        the_post();
        echo '<p>Published on: ';
        the_date();
        echo '</p>';
    }
}
?>

カスタムフォーマットとカスタムHTMLを追加する例

<?php
if (have_posts()) {
    while (have_posts()) {
        the_post();
        $date_format = 'F j, Y'; // 例: "January 1, 2024"
        echo '<p>Published on: ';
        the_date($date_format, '<strong>', '</strong>');
        echo '</p>';
    }
}
?>

カスタマイズ

the_date()関数を使用すると、同じ日の複数の投稿の場合、日付は1回だけ表示されます。そのため、すべての投稿で日付を表示するには、the_time()関数を使用するか、get_the_date()関数を使用することを検討してください。

<?php
if (have_posts()) {
    while (have_posts()) {
        the_post();
        $date_format = 'F j, Y'; // 例: "January 1, 2024"
        $date = get_the_date($date_format);
        echo '<p>Published on: <strong>' . esc_html($date) . '</strong></p>';
    }
}
?>

関連する関数

  • get_the_date(): 現在の投稿やページの公開日を取得します。表示するための追加のカスタマイズが可能です。
  • the_time(): 現在の投稿やページの公開時間を表示します。
  • get_the_time(): 現在の投稿やページの公開時間を取得します。
  • the_modified_date(): 現在の投稿やページの最終更新日を表示します。
  • get_the_modified_date(): 現在の投稿やページの最終更新日を取得します。