函数文档

get_the_date()

💡 云策文档标注

概述

get_the_date() 函数用于获取文章的发布日期,与 the_date() 不同,它总是返回日期。输出可通过 'get_the_date' 过滤器修改。

关键要点

  • 函数返回当前文章的发布日期,格式可自定义,默认使用 'date_format' 选项。
  • 接受两个可选参数:$format(PHP 日期格式字符串)和 $post(文章 ID 或 WP_Post 对象)。
  • 返回值类型为字符串、整数(当 $format 为 'U' 或 'G' 时)或 false(失败时)。
  • 内部使用 get_post_time() 获取本地化时间,并通过 apply_filters() 应用 'get_the_date' 钩子。
  • 相关函数包括 get_post_time()、apply_filters()、get_option() 和 get_post()。

代码示例

// 获取默认格式的日期
$date = get_the_date();

// 自定义格式,如“Monday January 11, 2017”
$post_date = get_the_date( 'l F j, Y' );
echo $post_date;

// 使用文章 ID 指定文章
$date = get_the_date( 'dS M Y', $post->ID ); // 输出如“15th Jan 2020”

注意事项

  • 与 the_date() 不同,get_the_date() 每次调用都返回日期,适合在循环外使用。
  • 如需获取修改日期,应使用 get_the_modified_date() 函数。
  • PHP 日期格式参考官方文档,如 'Y-m-d' 表示 ISO 8601 格式。

📄 原文内容

Retrieves the date of the post.

Description

Unlike the_date() this function will always return the date.
Modify output with the ‘get_the_date’ filter.

Parameters

$formatstringoptional
PHP date format. Defaults to the 'date_format' option.
$postint|WP_Postoptional
Post ID or WP_Post object. Default current post.

Default:null

Return

string|int|false Date the current post was written. False on failure.

Source

function get_the_date( $format = '', $post = null ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$_format = ! empty( $format ) ? $format : get_option( 'date_format' );

	$the_date = get_post_time( $_format, false, $post, true );

	/**
	 * Filters the date of the post.
	 *
	 * @since 3.0.0
	 *
	 * @param string|int $the_date Formatted date string or Unix timestamp if `$format` is 'U' or 'G'.
	 * @param string     $format   PHP date format.
	 * @param WP_Post    $post     The post object.
	 */
	return apply_filters( 'get_the_date', $the_date, $format, $post );
}

Hooks

apply_filters( ‘get_the_date’, string|int $the_date, string $format, WP_Post $post )

Filters the date of the post.

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 16 content

    If you need the modified date for schema purpose in ISO format