使い分けしよう!WordPressで投稿日時の表示に使える関数まとめ

使い分けしよう!WordPressで投稿日時の表示に使える関数まとめ

小林

小林

こんにちは。小林です。

WordPressのテーマを作成する歳に、日時の表示は、デザイン次第で出力の仕方が大幅に変ってくる部分です。従って、しっかり表示をコントロールしたいです。

さて、WordPressにおいて日付を扱う関数は様々準備されていますが、よく使うと思われる「投稿日を表示する際に利用する関数」についてちょっと見てみたいと思います。

WordPressで投稿日を表示する関数

the_date()

/**
 * @param string $d Optional. PHP date format defaults to the date_format option if not specified.
 * @param string $before Optional. Output before the date.
 * @param string $after Optional. Output after the date.
 * @param bool $echo Optional, default is display. Whether to echo the date or return it.
 * @return string|null Null if displaying, string if retrieving.
 */
function the_date( $d = '', $before = '', $after = '', $echo = true ) {

get_the_date()

/**
 * @param string $d Optional. PHP date format defaults to the date_format option if not specified.
 * @return string|null Null if displaying, string if retrieving.
 */
function get_the_date( $d = '' ) {

the_time()

/**
 * @param string $d Either 'G', 'U', or php date format.
 */
function the_time( $d = '' ) {

get_the_time()

/**
 * @param string $d Optional Either 'G', 'U', or php date format defaults to the value specified in the time_format option.
 * @param int|object $post Optional post ID or object. Default is global $post object.
 * @return string
 */
function get_the_time( $d = '', $post = null ) {

get_post_time()

/**
 * @param string $d Optional Either 'G', 'U', or php date format.
 * @param bool $gmt Optional, default is false. Whether to return the gmt time.
 * @param int|object $post Optional post ID or object. Default is global $post object.
 * @param bool $translate Whether to translate the time string
 * @return string
 */
function get_post_time( $d = 'U', $gmt = false, $post = null, $translate = false ) { // returns timestamp

投稿日を表示する関数それぞれの使い分け

実は、これらの処理が結構違うんですね。

それぞれ引数に着目していただきたいです。

the_date(),get_the_date(),the_time()

ループ内での利用が前提です。

get_the_time()とget_post_time()

the_date(),get_the_date(),the_time()がループ内での利用が前提なのに対して、引数で投稿を指定できます。

get_post_time()

さらに、日付まわりには、フォーマットや、GMT、翻訳の有無等様々なオプションがあると思いますが、それらを直接指定できるのは、get_post_time()だけなんですね。

まとめ

もちろん場合にもよりますが、そう言った意味では個人的にはget_post_time()が一番汎用的に使えると感じました。

LIGはWebサイト制作を支援しています。ご興味のある方は事業ぺージをぜひご覧ください。

Webサイト制作の実績・料金を見る

この記事のシェア数