函数文档

wp_resolve_post_date()

💡 云策文档标注

概述

wp_resolve_post_date() 函数用于解析和验证文章日期,确保返回有效的公历日期字符串。它通过 wp_checkdate 进行验证,并处理日期为空或无效时的回退逻辑。

关键要点

  • 函数接受两个参数:$post_date 和 $post_date_gmt,均为 MySQL 格式的日期字符串。
  • 如果 $post_date 为空或为 '0000-00-00 00:00:00',会优先检查 $post_date_gmt,否则使用当前时间。
  • 为保持向后兼容性,在 wp_insert_post 中,空 $post_date 和无效 $post_date_gmt 会返回 '1970-01-01 00:00:00' 而非 false。
  • 返回值为有效的日期字符串或 false(失败时)。

代码示例

function wp_resolve_post_date( $post_date = '', $post_date_gmt = '' ) {
    // If the date is empty, set the date to now.
    if ( empty( $post_date ) || '0000-00-00 00:00:00' === $post_date ) {
        if ( empty( $post_date_gmt ) || '0000-00-00 00:00:00' === $post_date_gmt ) {
            $post_date = current_time( 'mysql' );
        } else {
            $post_date = get_date_from_gmt( $post_date_gmt );
        }
    }

    // Validate the date.
    preg_match( '/^(d{4})-(d{1,2})-(d{1,2})/', $post_date, $matches );

    if ( empty( $matches ) || ! is_array( $matches ) || count( $matches ) View all references View on Trac View on GitHub

注意事项

  • 函数在 WordPress 5.7.0 版本中引入。
  • 相关函数包括 get_date_from_gmt()、wp_checkdate() 和 current_time()。
  • 被 wp_insert_post() 和 wp_update_nav_menu_item() 等函数使用。

📄 原文内容

Uses wp_checkdate to return a valid Gregorian-calendar value for post_date.

Description

If post_date is not provided, this first checks post_date_gmt if provided, then falls back to use the current time.

For back-compat purposes in wp_insert_post, an empty post_date and an invalid post_date_gmt will continue to return ‘1970-01-01 00:00:00’ rather than false.

Parameters

$post_datestringrequired
The date in mysql format (Y-m-d H:i:s).
$post_date_gmtstringrequired
The GMT date in mysql format (Y-m-d H:i:s).

Return

string|false A valid Gregorian-calendar date string, or false on failure.

Source

function wp_resolve_post_date( $post_date = '', $post_date_gmt = '' ) {
	// If the date is empty, set the date to now.
	if ( empty( $post_date ) || '0000-00-00 00:00:00' === $post_date ) {
		if ( empty( $post_date_gmt ) || '0000-00-00 00:00:00' === $post_date_gmt ) {
			$post_date = current_time( 'mysql' );
		} else {
			$post_date = get_date_from_gmt( $post_date_gmt );
		}
	}

	// Validate the date.
	preg_match( '/^(d{4})-(d{1,2})-(d{1,2})/', $post_date, $matches );

	if ( empty( $matches ) || ! is_array( $matches ) || count( $matches ) < 4 ) {
		return false;
	}

	$valid_date = wp_checkdate( $matches[2], $matches[3], $matches[1], $post_date );

	if ( ! $valid_date ) {
		return false;
	}
	return $post_date;
}

Changelog

Version Description
5.7.0 Introduced.