函数文档

wp_checkdate()

💡 云策文档标注

概述

wp_checkdate() 函数用于验证提供的日期是否符合公历(Gregorian calendar)的有效性。它基于 PHP 内置的 checkdate() 函数,并提供了一个可过滤的 Hook 以允许开发者自定义验证逻辑。

关键要点

  • 函数接受四个参数:$month(月份,整数)、$day(日,整数)、$year(年,整数)和 $source_date(源日期字符串)。
  • 返回布尔值:true 表示日期有效,false 表示无效。
  • 内部使用 PHP 的 checkdate() 函数进行核心验证,但仅在所有参数为数字时执行。
  • 提供了 apply_filters('wp_checkdate', $checkdate, $source_date) Hook,允许通过过滤器修改验证结果。
  • 在 WordPress 核心中广泛使用,例如在 wp_resolve_post_date()、WP_Date_Query::validate_date_values() 等函数中处理日期验证。
  • 自 WordPress 3.5.0 版本引入,无后续变更记录。

代码示例

function wp_checkdate( $month, $day, $year, $source_date ) {
    $checkdate = false;
    if ( is_numeric( $month ) && is_numeric( $day ) && is_numeric( $year ) ) {
        $checkdate = checkdate( (int) $month, (int) $day, (int) $year );
    }

    /**
     * Filters whether the given date is valid for the Gregorian calendar.
     *
     * @since 3.5.0
     *
     * @param bool   $checkdate   Whether the given date is valid.
     * @param string $source_date Date to check.
     */
    return apply_filters( 'wp_checkdate', $checkdate, $source_date );
}

注意事项

  • 参数 $month、$day 和 $year 必须为整数或可转换为整数的数字字符串,否则函数将返回 false。
  • Hook wp_checkdate 允许开发者干预验证过程,例如基于 $source_date 添加额外条件。
  • 文档中提到的“checkdate”链接可能已损坏,开发者需注意参考其他可靠资源。

📄 原文内容

Tests if the supplied date is valid for the Gregorian calendar.

Parameters

$monthintrequired
Month number.
$dayintrequired
Day number.
$yearintrequired
Year number.
$source_datestringrequired
The date to filter.

Return

bool True if valid date, false if not valid date.

Source

function wp_checkdate( $month, $day, $year, $source_date ) {
	$checkdate = false;
	if ( is_numeric( $month ) && is_numeric( $day ) && is_numeric( $year ) ) {
		$checkdate = checkdate( (int) $month, (int) $day, (int) $year );
	}

	/**
	 * Filters whether the given date is valid for the Gregorian calendar.
	 *
	 * @since 3.5.0
	 *
	 * @param bool   $checkdate   Whether the given date is valid.
	 * @param string $source_date Date to check.
	 */
	return apply_filters( 'wp_checkdate', $checkdate, $source_date );
}

Hooks

apply_filters( ‘wp_checkdate’, bool $checkdate, string $source_date )

Filters whether the given date is valid for the Gregorian calendar.

Changelog

Version Description
3.5.0 Introduced.

User Contributed Notes