函数文档

get_comment_time()

💡 云策文档标注

概述

get_comment_time() 函数用于获取指定评论的时间,支持自定义格式、GMT 时间、翻译和评论 ID 参数。它基于 WordPress 的 'time_format' 选项或提供的 PHP 日期格式返回格式化后的时间字符串。

关键要点

  • 函数返回当前或指定评论的格式化时间字符串。
  • 参数包括 $format(PHP 日期格式,默认使用 'time_format' 选项)、$gmt(是否使用 GMT 时间)、$translate(是否翻译时间,用于 feeds)和 $comment_id(评论 ID 或 WP_Comment 对象)。
  • 内部通过 get_comment() 获取评论数据,使用 mysql2date() 进行日期转换,并应用 'get_comment_time' 过滤器。
  • 从 WordPress 6.2.0 版本开始,新增了 $comment_id 参数,增强了灵活性。

代码示例

// Prints something like: 03:08:46 PM
echo get_comment_time( 'h:i:s A' );

// Prints something like: 3:08:46 pm
echo get_comment_time( 'g:i:s a' );

// Prints 24 hour time, something like: 0800
echo get_comment_time( 'Hi' );

// Prints 24 hour time, something like: 800
echo get_comment_time( 'Gi' );

注意事项

  • 如果评论不存在(get_comment() 返回 null),函数返回空字符串。
  • 默认情况下,时间会根据 'time_format' 选项格式化,并可能被翻译,适用于国际化场景。
  • 开发者可以通过 'get_comment_time' 过滤器自定义返回的时间值。

📄 原文内容

Retrieves the comment time of the current comment.

Parameters

$formatstringoptional
PHP date format. Defaults to the 'time_format' option.
$gmtbooloptional
Whether to use the GMT date.

Default:false

$translatebooloptional
Whether to translate the time (for use in feeds).

Default:true

$comment_idint|WP_Commentoptional
WP_Comment or ID of the comment for which to get the time.
Default current comment.

Return

string The formatted time.

Source

function get_comment_time( $format = '', $gmt = false, $translate = true, $comment_id = 0 ) {
	$comment = get_comment( $comment_id );

	if ( null === $comment ) {
		return '';
	}

	$comment_date = $gmt ? $comment->comment_date_gmt : $comment->comment_date;

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

	$comment_time = mysql2date( $_format, $comment_date, $translate );

	/**
	 * Filters the returned comment time.
	 *
	 * @since 1.5.0
	 *
	 * @param string|int $comment_time The comment time, formatted as a date string or Unix timestamp.
	 * @param string     $format       PHP date format.
	 * @param bool       $gmt          Whether the GMT date is in use.
	 * @param bool       $translate    Whether the time is translated.
	 * @param WP_Comment $comment      The comment object.
	 */
	return apply_filters( 'get_comment_time', $comment_time, $format, $gmt, $translate, $comment );
}

Hooks

apply_filters( ‘get_comment_time’, string|int $comment_time, string $format, bool $gmt, bool $translate, WP_Comment $comment )

Filters the returned comment time.

Changelog

Version Description
6.2.0 Added the $comment_id parameter.
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Examples of Different Time Formats

    // Prints something like: 03:08:46 PM
    echo get_comment_time( 'h:i:s A' );
    
    // Prints something like: 3:08:46 pm
    echo get_comment_time( 'g:i:s a' );
    
    // Prints 24 hour time, something like: 0800
    echo get_comment_time( 'Hi' );
    
    // Prints 24 hour time, something like: 800
    echo get_comment_time( 'Gi' );