LoginSignup
0
1

More than 1 year has passed since last update.

【Wordpress】最終更新日時を表示するショートコード作ったよ

Last updated at Posted at 2022-02-24

WordPressの勉強がてら、投稿ページや固定ページに埋め込めるショートコードを作りました。
以下のソースコードをテーマファイル内の 「functions.php」 内にコピーしてお使いください。
投稿ページ・固定ページの使用したい箇所に [LastModDate] と入力すれば、年/月/日 時間:分:秒 のように自動で表示されます。
※functions.phpの中身をいじりますので、エラーが発生する可能性があります。必ず事前にバックアップをとった上で、自己責任で編集してください。
万が一のことがあっても中の人は責任を負えません……:sob:

functions.php
//最終更新日時を取得→表示するショートコードを作る関数
function last_modified_func($atts, $format)
{
	$pdate = get_the_date('Ymd');
	$mdate = get_the_modified_date('Ymd');
	$modified_year = get_the_modified_date('Y/');
	$modified_month = get_the_modified_date('m/');
	$modified_day = get_the_modified_date('d');
	$modified_hour = get_the_modified_time('H:');
    $modified_minute = get_the_modified_time('i:');
	$modified_second = get_the_modified_time('s');
	$mod = shortcode_atts( array(
		'modYear' => $modified_year,
		'modMonth' => $modified_month,
		'modDay' => $modified_day,
		'modHour' => $modified_hour,
		'modMinute' => $modified_minute,
		'modSec' => $modified_second
	), $atts );
	
	//新規投稿時は表示しない
	if($pdate > $mdate){
	   return null;	
	} else {
	  $msg = $mod['modYear'] . $mod['modMonth']. $mod['modDay'] . ' ' . $mod['modHour'] . $mod['modMinute'] .  $mod['modSec'];
	return $msg;	
	}
	
}
add_shortcode('LastModDate','last_modified_func');

関数の解説

$pdate = 投稿日の取得

$mdate = 編集日の取得

$modified_year = 編集日の年の部分(西暦4桁で取得)

$modified_month = 編集日の月の部分(先頭に0をつける)

$modified_day = 編集日の日の部分(先頭に0をつける)

$modified_hour = 編集時間の時の部分(24時間単位)

$modified_minute = 編集時間の分の部分(先頭に0をつける)

$modified_second = 編集時間の秒の部分(先頭に0をつける)


秒がいらない場合は、$msg内の $mod['modSec']を削除してください✌('ω')


WordPress1年目のひよっこが作成していますので、表示がおかしい等エラーがありましたら、お手数ですがコメントでご連絡ください。直ちに修正します:mask:

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1