WordPressで公開日と更新日を表示するテンプレートタグの書き方です。
更新日の取得
更新日、つまり投稿が最後に変更された日はthe_modified_date()で取得できます。ただ、この日付はサムネイルを更新しただけでも更新される日付なので注意が必要ですね。
<?php the_modified_date(); ?>
引数を指定しない場合は、WordPressの管理画面で指定してある日付形式に基づいた表示になります。テンプレート側で日付の表示方法を指定したい場合は以下。Y=year(年)、m=month(月)、d=date(日)です。
<?php the_modified_date('Y.m.d'); ?>
公開日と更新日が異なる場合のみ更新日を表示
公開日と更新日が異なる場合のみ更新日を表示する場合は、以下のように記述します。
<?php the_time(); ?>
<?php if(get_the_time('Y.m.d') != get_the_modified_date('Y.m.d')): ?>
<?php the_modified_date(); ?>
<?php endif;?>
更新日はあくまでも投稿が最後に変更された日なので、公開日から記事を修正していない場合は公開日=更新日となります。なので、公開日が更新日と違う場合という条件分岐をしています。
また、‘Y.m.d’という引数を指定しないと、データ自体には時間も含まれているので、同じ日に内容修正をした場合も更新とみなされ同じ日付が並んでしまいます。なので、この引数は重要です。
公開日と更新日が異なる場合は更新日のみ表示
公開日と更新日が異なる場合に更新日のみ表示する場合は以下のように条件分岐します。
<?php if(get_the_time('Y.m.d') != get_the_modified_date('Y.m.d')):?>
<?php the_modified_date(); ?>
<?php else:?>
<?php the_time(); ?>
<?php endif;?>
single.phpで実際に使う場合
実際にsingle.phpで使う場合は私は以下のようにしました!
<time datetime="<?php echo get_the_modified_date('Y-m-d'); ?>">
<span><?php the_time(); ?></span>
<?php if(get_the_time('Y.m.d') != get_the_modified_date('Y.m.d')):?>
<span><?php the_modified_date(); ?></span>
<?php endif;?>
</time>
timeタグのdatetimeはget_the_modified_dateにしています。見た目は公開日と更新日が表示されていますが、検索で表示される記事の日付は更新していない場合は公開日、更新した場合は更新日になります。
公式リファレンス
get_the_modified_dateの詳細は、下記公式リファレンスをご参照ください。
https://developer.wordpress.org/reference/functions/the_modified_date/