WordPressで「特定の記事の最終更新日」をトップページや固定ページに表示したい場面は多い。
しかしテンプレートファイルを直接編集するのは手間がかかるうえ、テーマアップデートで上書きされる危険もある。
この問題は、ショートコードを自作してfunctions.phpに登録することで簡潔に解決できる。
環境と前提
本稿の内容はWordPress 6.x系を前提としている。
テーマは任意だが、functions.php にコードを追記できる環境であることが条件である。
子テーマを使っている場合は、子テーマ側に記述することで親テーマの更新にも耐えられる。
ショートコードの実装
最終更新日を出力するショートコード [updated] を以下のように定義する。
// [updated id="123" format="Y-m-d"]
function shortcode_post_updated( $atts ) {
$atts = shortcode_atts(
array(
'id' => null,
'format' => 'Y-m-d',
),
$atts,
'updated'
);
if ( ! $atts['id'] ) {
return ''; // id未指定なら出力なし
}
$updated = get_the_modified_time( $atts['format'], $atts['id'] );
if ( ! $updated ) {
return '';
}
return esc_html( $updated );
}
add_shortcode( 'updated', 'shortcode_post_updated' );
このコードを functions.php に追加すれば、ショートコード [updated id="123"] で記事ID 123 の最終更新日を表示できる。format 属性を指定すれば日付フォーマットを自由に変更できる。
例:
[updated id="123" format="Y年n月j日"]
出力結果:2025年10月19日
タイトル付きの拡張版
記事タイトルと更新日を併記したい場合は、次のようにショートコードを拡張できる。
// [updated_with_title id="123" format="Y-m-d"]
function shortcode_post_updated_with_title( $atts ) {
$atts = shortcode_atts(
array(
'id' => null,
'format' => 'Y-m-d',
),
$atts,
'updated_with_title'
);
if ( ! $atts['id'] ) {
return '';
}
$post = get_post( $atts['id'] );
if ( ! $post ) {
return '';
}
$title = get_the_title( $post );
$updated = get_the_modified_time( $atts['format'], $atts['id'] );
return esc_html( $title . '(更新日: ' . $updated . ')' );
}
add_shortcode( 'updated_with_title', 'shortcode_post_updated_with_title' );
これにより、
[updated_with_title id="45" format="Y/m/d"]
と書くだけで
「記事タイトル(更新日: 2025/10/19)」
という形式で表示できる。
実運用上の注意点
このショートコードはループ外で動作するため、トップページや固定ページの任意の位置に埋め込める。
ただし、キャッシュ系プラグイン(WP Super Cache、LiteSpeed Cacheなど)を使用している場合は、更新後にキャッシュを手動削除しないと表示が反映されない場合がある。
また、日付の取得には get_the_modified_time() を使用しているため、テーマによってはタイムゾーン設定が影響することがある。必要に応じて get_post_modified_time() に置き換えてもよい。
まとめ
ショートコード化することで、テンプレート編集を避けながら任意の場所に更新日を表示できるようになった。
WordPressの柔軟性を保ったまま、メンテナンス性を高めるシンプルな実装例として有用である。