「代わりにcurrent_datetime()を使え」とのこと。
current_datetime()関数の戻り値は、PHPのDateTimeImmutableオブジェクトである。
var_dump( current_datetime() );
// current_datetime()の戻り値 DateTimeImmutableオブジェクト
object(DateTimeImmutable)[1853]
public 'date' => string '2024-10-20 15:52:57.897423' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'Asia/Tokyo' (length=10)
DateTimeImmutableオブジェクトを知らなかったので、current_datetime()->dateとやってみたがdateプロパティの値が取れなかった。
調べてみると、
このクラスは DateTime と同じ振る舞いをします。
https://www.php.net/manual/ja/class.datetimeimmutable.php
と書いてある。
現在日時タイムスタンプ値の取得
というわけで、DateTimeオブジェクトのgetTimestamp()メソッドで取得する。
5.3までcurrent_time( ‘timestamp’ )で取得していたタイムスタンプ値は、下記のようにcurrent_datetime()の戻り値(オブジェクト)から取得できる。
// wordpressサイトに設定しているタイムゾーンに基づいた現在日時のタイムスタンプ値を取得
$nowTimeStamp = current_datetime()->getTimestamp();
特定日時タイムスタンプ値の取得
特定日時(現在日時でない)のタイムスタンプ値を取得するには、まず、DateTimeImmutableオブジェクトを生成する。第1引数に日付/時刻文字列、第2引数にサイトに設定しているタイムゾーンのDateTimeZoneオブジェクトを指定。生成したDateTimeImmutableオブジェクトからgetTimestamp()メソッドでタイムスタンプ値を取得する。
$sample_date_obj = new DateTimeImmutable( '2024-10-15 15:52:57', wp_timezone() );
$sample_date_stamp = $sample_date_obj->getTimestamp();
var_dump( $sample_date_stamp );
int 1728975177
wordpress公式見解では非推奨としているが、date_default_timezone_set()を使って一時的にPHPのタイムゾーンを変えた方が簡単なことも多いと思う。
https://make.wordpress.org/core/2019/09/23/date-time-improvements-wp-5-3/
https://kinsta.com/jp/blog/wordpress-5-3/
WordPress5.3, 日付/時刻取得の変更と新しい関数。DateTimeクラスが基準になる。
コメントを残す