wp_checkdate()
Checks the validity of a date according to the Gregorian calendar.
This is a wrapper for the PHP function checkdate().
1 time — 0.00002 sec (very fast) | 50000 times — 0.10 sec (speed of light)
Hooks from the function
Returns
true|false. Boolean. true if the date is valid, false otherwise.
Usage
if( wp_checkdate( $month, $day, $year, $source_date ) ){
// check passed, do something
}
- $month(int) (required)
- Month number (1-12).
- $day(int) (required)
- Day number (1-31).
- $year(int) (required)
- Year.
- $source_date(string) (required)
- The original date in which the specified year/month/day is checked. Provided for passing to the filter. For example 2008-10-24
Examples
#1 An example from the WordPress core
/*
* If the date is not set ( new post or draft)
* if it is not a draft or the date was changed in the process of writing.
*/
if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
$post_date = current_time( 'mysql' );
}
else {
$post_date = $postarr['post_date'];
}
// Date Validation.
$mm = substr( $post_date, 5, 2 );
$jj = substr( $post_date, 8, 2 );
$aa = substr( $post_date, 0, 4 );
$valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
if ( ! $valid_date ) {
if ( $wp_error ) {
//The specified date is incorrect.
return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
}
else {
return 0;
}
} #2 Another example from the WordPress core
if ( get_query_var( 'day' ) && get_query_var( 'monthnum' ) && get_query_var( 'year' ) ) {
$year = get_query_var( 'year' );
$month = get_query_var( 'monthnum' );
$day = get_query_var( 'day' );
$date = sprintf( '%04d-%02d-%02d', $year, $month, $day );
if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
$redirect_url = get_month_link( $year, $month );
}
}
Changelog
| Since 3.5.0 | Introduced. |
wp_checkdate() wp checkdate code WP 6.9.1
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 );
}