函数文档

get_comment_date()

💡 云策文档标注

概述

get_comment_date() 函数用于获取指定评论的日期,支持自定义日期格式,并可通过过滤器进行修改。它是 WordPress 评论处理中的核心函数之一。

关键要点

  • 函数返回评论日期字符串,默认使用 WordPress 设置的日期格式。
  • 参数 $format 可选,指定 PHP 日期格式;$comment_id 可选,可接受评论 ID 或 WP_Comment 对象,默认为当前评论。
  • 内部使用 mysql2date() 转换 MySQL 日期字符串,并应用 get_comment_date 过滤器。
  • 从 WordPress 4.4.0 开始,$comment_id 支持 WP_Comment 对象。

代码示例

// 基本用法:获取当前评论日期,使用默认格式
$comment_date = get_comment_date();

// 自定义格式:输出类似 "Saturday, November 6th, 2010"
$d = "l, F jS, Y";
$comment_date = get_comment_date($d, $comment_ID);
echo $comment_date;

// 不同格式示例
echo get_comment_date('l jS \of F Y'); // 输出:Monday 8th of August 2005
echo get_comment_date('D M j Y'); // 输出:Mon Mar 8 2012
echo get_comment_date('d\/m\/Y'); // 输出:07/08/2017

注意事项

  • 日期格式需遵循 PHP date() 函数规范,可参考 WordPress 日期和时间格式化文档。
  • 函数返回字符串,可直接用于输出或进一步处理。
  • 相关函数包括 comment_date()(直接显示日期)、get_comment()(获取评论数据)和 mysql2date()(日期转换)。

📄 原文内容

Retrieves the comment date of the current comment.

Parameters

$formatstringoptional
PHP date format. Defaults to the 'date_format' option.
$comment_idint|WP_Commentoptional
WP_Comment or ID of the comment for which to get the date.
Default current comment.

Return

string The comment’s date.

More Information

The date format can be in a format specified in Formatting Date and Time

Source

function get_comment_date( $format = '', $comment_id = 0 ) {
	$comment = get_comment( $comment_id );

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

	$comment_date = mysql2date( $_format, $comment->comment_date );

	/**
	 * Filters the returned comment date.
	 *
	 * @since 1.5.0
	 *
	 * @param string|int $comment_date Formatted date string or Unix timestamp.
	 * @param string     $format       PHP date format.
	 * @param WP_Comment $comment      The comment object.
	 */
	return apply_filters( 'get_comment_date', $comment_date, $format, $comment );
}

Hooks

apply_filters( ‘get_comment_date’, string|int $comment_date, string $format, WP_Comment $comment )

Filters the returned comment date.

Changelog

Version Description
4.4.0 Added the ability for $comment_id to also accept a WP_Comment object.
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Display a beautiful, human-readable, comment time:

    function smk_get_comment_time( $comment_id = 0 ){
    	return sprintf( 
    		_x( '%s ago', 'Human-readable time', 'text-domain' ), 
    		human_time_diff( 
    			get_comment_date( 'U', $comment_id ), 
    			current_time( 'timestamp' ) 
    		) 
    	);
    }

    When called it will convert the time and return something like:

    "1 min ago", "3 mins ago", "17 hours ago", "7 days ago", "2 weeks ago", etc....

    Use this function because it’s more user friendly.