3 * Class for generating SQL clauses that filter a primary query according to date.
5 * `WP_Date_Query` is a helper that allows primary query classes, such as {@see WP_Query},
6 * to filter their results by date columns, by generating `WHERE` subclauses to be attached
7 * to the primary SQL query string.
9 * Attempting to filter by an invalid date value (eg month=13) will generate SQL that will
10 * return no results. In these cases, a _doing_it_wrong() error notice is also thrown.
11 * See {@link WP_Date_Query::validate_date_values()}.
13 * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page.
19 * Array of date queries.
21 * See {@see WP_Date_Query::__construct()} for information on date query arguments.
27 public $queries = array();
30 * The default relation between top-level queries. Can be either 'AND' or 'OR'.
36 public $relation = 'AND';
39 * The column to query against. Can be changed via the query arguments.
45 public $column = 'post_date';
48 * The value comparison operator. Can be changed via the query arguments.
54 public $compare = '=';
57 * Supported time-related parameter keys.
63 public $time_keys = array( 'after', 'before', 'year', 'month', 'monthnum', 'week', 'w', 'dayofyear', 'day', 'dayofweek', 'dayofweek_iso', 'hour', 'minute', 'second' );
69 * @since 4.0.0 The $inclusive logic was updated to include all times within the date range.
70 * @since 4.1.0 Introduced 'dayofweek_iso' time type parameter.
73 * @param array $date_query {
74 * Array of date query clauses.
77 * @type string $column Optional. The column to query against. If undefined, inherits the value of
78 * the $default_column parameter. Default 'post_date'. Accepts 'post_date',
79 * 'post_date_gmt', 'post_modified','post_modified_gmt', 'comment_date',
81 * @type string $compare Optional. The comparison operator.
82 * Accepts '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN'. Default '='.
83 * 'BETWEEN', 'NOT BETWEEN'.
84 * @type string $relation Optional. The boolean relationship between the date queries.
85 * Accepts 'OR', 'AND'. Default 'OR'.
87 * Optional. An array of first-order clause parameters, or another fully-formed date query.
89 * @type string|array $before Optional. Date to retrieve posts before. Accepts strtotime()-compatible
90 * string, or array of 'year', 'month', 'day' values. {
92 * @type string $year The four-digit year. Default empty. Accepts any four-digit year.
93 * @type string $month Optional when passing array.The month of the year.
94 * Default (string:empty)|(array:1). Accepts numbers 1-12.
95 * @type string $day Optional when passing array.The day of the month.
96 * Default (string:empty)|(array:1). Accepts numbers 1-31.
98 * @type string|array $after Optional. Date to retrieve posts after. Accepts strtotime()-compatible
99 * string, or array of 'year', 'month', 'day' values. {
101 * @type string $year The four-digit year. Default empty. Accepts any four-digit year.
102 * @type string $month Optional when passing array.The month of the year.
103 * Default (string:empty)|(array:12). Accepts numbers 1-12.
104 * @type string $day Optional when passing array.The day of the month.
105 * Default (string:empty)|(array:last day of month). Accepts numbers 1-31.
107 * @type string $column Optional. Used to add a clause comparing a column other than the column
108 * specified in the top-level $column parameter. Default is the value
109 * of top-level $column. Accepts 'post_date', 'post_date_gmt',
110 * 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt'.
111 * @type string $compare Optional. The comparison operator. Default '='.
112 * Accepts '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN',
113 * 'BETWEEN', 'NOT BETWEEN'.
114 * @type bool $inclusive Optional. Include results from dates specified in 'before' or
115 * 'after'. Default false.
116 * @type int $year Optional. The four-digit year number. Default empty. Accepts
117 * any four-digit year.
118 * @type int $month Optional. The two-digit month number. Default empty.
119 * Accepts numbers 1-12.
120 * @type int $week Optional. The week number of the year. Default empty.
121 * Accepts numbers 0-53.
122 * @type int $dayofyear Optional. The day number of the year. Default empty.
123 * Accepts numbers 1-366.
124 * @type int $day Optional. The day of the month. Default empty.
125 * Accepts numbers 1-31.
126 * @type int $dayofweek Optional. The day number of the week. Default empty.
127 * Accepts numbers 1-7 (1 is Sunday).
128 * @type int $dayofweek_iso Optional. The day number of the week (ISO). Accepts numbers 1-7
129 * (1 is Monday). Default empty.
130 * @type int $hour Optional. The hour of the day. Default empty. Accepts numbers 0-23.
131 * @type int $minute Optional. The minute of the hour. Default empty. Accepts
133 * @type int $second Optional. The second of the minute. Default empty.
134 * Accepts numbers 0-60.
138 * @param array $default_column Optional. Default column to query against. Default 'post_date'.
139 * Accepts 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt',
140 * 'comment_date', 'comment_date_gmt'.
142 public function __construct( $date_query, $default_column = 'post_date' ) {
144 if ( isset( $date_query['relation'] ) && 'OR' === strtoupper( $date_query['relation'] ) ) {
145 $this->relation = 'OR';
147 $this->relation = 'AND';
150 if ( ! is_array( $date_query ) ) {
154 // Support for passing time-based keys in the top level of the $date_query array.
155 if ( ! isset( $date_query[0] ) && ! empty( $date_query ) ) {
156 $date_query = array( $date_query );
159 if ( empty( $date_query ) ) {
163 if ( ! empty( $date_query['column'] ) ) {
164 $date_query['column'] = esc_sql( $date_query['column'] );
166 $date_query['column'] = esc_sql( $default_column );
169 $this->column = $this->validate_column( $this->column );
171 $this->compare = $this->get_compare( $date_query );
173 $this->queries = $this->sanitize_query( $date_query );
179 * Recursive-friendly query sanitizer.
181 * Ensures that each query-level clause has a 'relation' key, and that
182 * each first-order clause contains all the necessary keys from
188 * @param array $queries
189 * @param array $parent_query
191 * @return array Sanitized queries.
193 public function sanitize_query( $queries, $parent_query = null ) {
194 $cleaned_query = array();
197 'column' => 'post_date',
202 // Numeric keys should always have array values.
203 foreach ( $queries as $qkey => $qvalue ) {
204 if ( is_numeric( $qkey ) && ! is_array( $qvalue ) ) {
205 unset( $queries[ $qkey ] );
209 // Each query should have a value for each default key. Inherit from the parent when possible.
210 foreach ( $defaults as $dkey => $dvalue ) {
211 if ( isset( $queries[ $dkey ] ) ) {
215 if ( isset( $parent_query[ $dkey ] ) ) {
216 $queries[ $dkey ] = $parent_query[ $dkey ];
218 $queries[ $dkey ] = $dvalue;
222 // Validate the dates passed in the query.
223 if ( $this->is_first_order_clause( $queries ) ) {
224 $this->validate_date_values( $queries );
227 foreach ( $queries as $key => $q ) {
228 if ( ! is_array( $q ) || in_array( $key, $this->time_keys, true ) ) {
229 // This is a first-order query. Trust the values and sanitize when building SQL.
230 $cleaned_query[ $key ] = $q;
232 // Any array without a time key is another query, so we recurse.
233 $cleaned_query[] = $this->sanitize_query( $q, $queries );
237 return $cleaned_query;
241 * Determine whether this is a first-order clause.
243 * Checks to see if the current clause has any time-related keys.
244 * If so, it's first-order.
246 * @param array $query Query clause.
247 * @return bool True if this is a first-order clause.
249 protected function is_first_order_clause( $query ) {
250 $time_keys = array_intersect( $this->time_keys, array_keys( $query ) );
251 return ! empty( $time_keys );
255 * Determines and validates what comparison operator to use.
260 * @param array $query A date query or a date subquery.
261 * @return string The comparison operator.
263 public function get_compare( $query ) {
264 if ( ! empty( $query['compare'] ) && in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
265 return strtoupper( $query['compare'] );
267 return $this->compare;
271 * Validates the given date_query values and triggers errors if something is not valid.
273 * Note that date queries with invalid date ranges are allowed to
274 * continue (though of course no items will be found for impossible dates).
275 * This method only generates debug notices for these cases.
280 * @param array $date_query The date_query array.
281 * @return bool True if all values in the query are valid, false if one or more fail.
283 public function validate_date_values( $date_query = array() ) {
284 if ( empty( $date_query ) ) {
291 * Validate 'before' and 'after' up front, then let the
292 * validation routine continue to be sure that all invalid
293 * values generate errors too.
295 if ( array_key_exists( 'before', $date_query ) && is_array( $date_query['before'] ) ){
296 $valid = $this->validate_date_values( $date_query['before'] );
299 if ( array_key_exists( 'after', $date_query ) && is_array( $date_query['after'] ) ){
300 $valid = $this->validate_date_values( $date_query['after'] );
303 // Array containing all min-max checks.
304 $min_max_checks = array();
307 if ( array_key_exists( 'year', $date_query ) ) {
308 // If a year exists in the date query, we can use it to get the days.
309 $max_days_of_year = date( 'z', mktime( 0, 0, 0, 12, 31, $date_query['year'] ) ) + 1;
311 // otherwise we use the max of 366 (leap-year)
312 $max_days_of_year = 366;
315 $min_max_checks['dayofyear'] = array(
317 'max' => $max_days_of_year
321 $min_max_checks['dayofweek'] = array(
327 $min_max_checks['dayofweek_iso'] = array(
333 $min_max_checks['month'] = array(
339 if ( array_key_exists( 'year', $date_query ) ) {
340 // If we have a specific year, use it to calculate number of weeks.
341 $date = new DateTime();
342 $date->setISODate( $date_query['year'], 53 );
343 $week_count = $date->format( "W" ) === "53" ? 53 : 52;
346 // Otherwise set the week-count to a maximum of 53.
350 $min_max_checks['week'] = array(
356 $min_max_checks['day'] = array(
362 $min_max_checks['hour'] = array(
368 $min_max_checks['minute'] = array(
373 // Seconds per minute.
374 $min_max_checks['second'] = array(
379 // Concatenate and throw a notice for each invalid value.
380 foreach ( $min_max_checks as $key => $check ) {
381 if ( ! array_key_exists( $key, $date_query ) ) {
385 $is_between = $date_query[ $key ] >= $check['min'] && $date_query[ $key ] <= $check['max'];
387 if ( ! $is_between ) {
390 /* translators: Date query invalid date message: 1: invalid value, 2: type of value, 3: minimum valid value, 4: maximum valid value */
391 __( 'Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.' ),
392 '<code>' . esc_html( $date_query[ $key ] ) . '</code>',
393 '<code>' . esc_html( $key ) . '</code>',
394 '<code>' . esc_html( $check['min'] ) . '</code>',
395 '<code>' . esc_html( $check['max'] ) . '</code>'
398 _doing_it_wrong( __CLASS__, $error, '4.1.0' );
404 // If we already have invalid date messages, don't bother running through checkdate().
409 $day_month_year_error_msg = '';
411 $day_exists = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] );
412 $month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] );
413 $year_exists = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] );
415 if ( $day_exists && $month_exists && $year_exists ) {
416 // 1. Checking day, month, year combination.
417 if ( ! wp_checkdate( $date_query['month'], $date_query['day'], $date_query['year'], sprintf( '%s-%s-%s', $date_query['year'], $date_query['month'], $date_query['day'] ) ) ) {
418 /* translators: 1: year, 2: month, 3: day of month */
419 $day_month_year_error_msg = sprintf(
420 __( 'The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.' ),
421 '<code>' . esc_html( $date_query['year'] ) . '</code>',
422 '<code>' . esc_html( $date_query['month'] ) . '</code>',
423 '<code>' . esc_html( $date_query['day'] ) . '</code>'
429 } else if ( $day_exists && $month_exists ) {
431 * 2. checking day, month combination
432 * We use 2012 because, as a leap year, it's the most permissive.
434 if ( ! wp_checkdate( $date_query['month'], $date_query['day'], 2012, sprintf( '2012-%s-%s', $date_query['month'], $date_query['day'] ) ) ) {
435 /* translators: 1: month, 2: day of month */
436 $day_month_year_error_msg = sprintf(
437 __( 'The following values do not describe a valid date: month %1$s, day %2$s.' ),
438 '<code>' . esc_html( $date_query['month'] ) . '</code>',
439 '<code>' . esc_html( $date_query['day'] ) . '</code>'
446 if ( ! empty( $day_month_year_error_msg ) ) {
447 _doing_it_wrong( __CLASS__, $day_month_year_error_msg, '4.1.0' );
454 * Validates a column name parameter.
456 * Column names without a table prefix (like 'post_date') are checked against a whitelist of
457 * known tables, and then, if found, have a table prefix (such as 'wp_posts.') prepended.
458 * Prefixed column names (such as 'wp_posts.post_date') bypass this whitelist check,
459 * and are only sanitized to remove illegal characters.
464 * @param string $column The user-supplied column name.
465 * @return string A validated column name value.
467 public function validate_column( $column ) {
470 $valid_columns = array(
471 'post_date', 'post_date_gmt', 'post_modified',
472 'post_modified_gmt', 'comment_date', 'comment_date_gmt',
476 // Attempt to detect a table prefix.
477 if ( false === strpos( $column, '.' ) ) {
479 * Filter the list of valid date query columns.
482 * @since 4.1.0 Added 'user_registered' to the default recognized columns.
484 * @param array $valid_columns An array of valid date query columns. Defaults
485 * are 'post_date', 'post_date_gmt', 'post_modified',
486 * 'post_modified_gmt', 'comment_date', 'comment_date_gmt',
489 if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ) ) ) {
490 $column = 'post_date';
493 $known_columns = array(
494 $wpdb->posts => array(
500 $wpdb->comments => array(
504 $wpdb->users => array(
509 // If it's a known column name, add the appropriate table prefix.
510 foreach ( $known_columns as $table_name => $table_columns ) {
511 if ( in_array( $column, $table_columns ) ) {
512 $column = $table_name . '.' . $column;
519 // Remove unsafe characters.
520 return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column );
524 * Generate WHERE clause to be appended to a main query.
529 * @return string MySQL WHERE clause.
531 public function get_sql() {
532 $sql = $this->get_sql_clauses();
534 $where = $sql['where'];
537 * Filter the date query WHERE clause.
541 * @param string $where WHERE clause of the date query.
542 * @param WP_Date_Query $this The WP_Date_Query instance.
544 return apply_filters( 'get_date_sql', $where, $this );
548 * Generate SQL clauses to be appended to a main query.
550 * Called by the public {@see WP_Date_Query::get_sql()}, this method
551 * is abstracted out to maintain parity with the other Query classes.
557 * Array containing JOIN and WHERE SQL clauses to append to the main query.
559 * @type string $join SQL fragment to append to the main JOIN clause.
560 * @type string $where SQL fragment to append to the main WHERE clause.
563 protected function get_sql_clauses() {
564 $sql = $this->get_sql_for_query( $this->queries );
566 if ( ! empty( $sql['where'] ) ) {
567 $sql['where'] = ' AND ' . $sql['where'];
574 * Generate SQL clauses for a single query array.
576 * If nested subqueries are found, this method recurses the tree to
577 * produce the properly nested SQL.
582 * @param array $query Query to parse.
583 * @param int $depth Optional. Number of tree levels deep we currently are.
584 * Used to calculate indentation. Default 0.
586 * Array containing JOIN and WHERE SQL clauses to append to a single query array.
588 * @type string $join SQL fragment to append to the main JOIN clause.
589 * @type string $where SQL fragment to append to the main WHERE clause.
592 protected function get_sql_for_query( $query, $depth = 0 ) {
604 for ( $i = 0; $i < $depth; $i++ ) {
608 foreach ( $query as $key => $clause ) {
609 if ( 'relation' === $key ) {
610 $relation = $query['relation'];
611 } else if ( is_array( $clause ) ) {
613 // This is a first-order clause.
614 if ( $this->is_first_order_clause( $clause ) ) {
615 $clause_sql = $this->get_sql_for_clause( $clause, $query );
617 $where_count = count( $clause_sql['where'] );
618 if ( ! $where_count ) {
619 $sql_chunks['where'][] = '';
620 } else if ( 1 === $where_count ) {
621 $sql_chunks['where'][] = $clause_sql['where'][0];
623 $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
626 $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
627 // This is a subquery, so we recurse.
629 $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
631 $sql_chunks['where'][] = $clause_sql['where'];
632 $sql_chunks['join'][] = $clause_sql['join'];
637 // Filter to remove empties.
638 $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
639 $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
641 if ( empty( $relation ) ) {
645 // Filter duplicate JOIN clauses and combine into a single string.
646 if ( ! empty( $sql_chunks['join'] ) ) {
647 $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
650 // Generate a single WHERE clause with proper brackets and indentation.
651 if ( ! empty( $sql_chunks['where'] ) ) {
652 $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
659 * Turns a single date clause into pieces for a WHERE clause.
661 * A wrapper for get_sql_for_clause(), included here for backward
662 * compatibility while retaining the naming convention across Query classes.
667 * @param array $query Date query arguments.
669 * Array containing JOIN and WHERE SQL clauses to append to the main query.
671 * @type string $join SQL fragment to append to the main JOIN clause.
672 * @type string $where SQL fragment to append to the main WHERE clause.
675 protected function get_sql_for_subquery( $query ) {
676 return $this->get_sql_for_clause( $query, '' );
680 * Turns a first-order date query into SQL for a WHERE clause.
685 * @param array $query Date query clause.
686 * @param array $parent_query Parent query of the current date query.
688 * Array containing JOIN and WHERE SQL clauses to append to the main query.
690 * @type string $join SQL fragment to append to the main JOIN clause.
691 * @type string $where SQL fragment to append to the main WHERE clause.
694 protected function get_sql_for_clause( $query, $parent_query ) {
697 // The sub-parts of a $where part.
698 $where_parts = array();
700 $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
702 $column = $this->validate_column( $column );
704 $compare = $this->get_compare( $query );
706 $inclusive = ! empty( $query['inclusive'] );
708 // Assign greater- and less-than values.
718 if ( ! empty( $query['after'] ) )
719 $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) );
721 if ( ! empty( $query['before'] ) )
722 $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) );
724 // Specific value queries.
726 if ( isset( $query['year'] ) && $value = $this->build_value( $compare, $query['year'] ) )
727 $where_parts[] = "YEAR( $column ) $compare $value";
729 if ( isset( $query['month'] ) && $value = $this->build_value( $compare, $query['month'] ) )
730 $where_parts[] = "MONTH( $column ) $compare $value";
731 else if ( isset( $query['monthnum'] ) && $value = $this->build_value( $compare, $query['monthnum'] ) )
732 $where_parts[] = "MONTH( $column ) $compare $value";
734 if ( isset( $query['week'] ) && false !== ( $value = $this->build_value( $compare, $query['week'] ) ) )
735 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
736 else if ( isset( $query['w'] ) && false !== ( $value = $this->build_value( $compare, $query['w'] ) ) )
737 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
739 if ( isset( $query['dayofyear'] ) && $value = $this->build_value( $compare, $query['dayofyear'] ) )
740 $where_parts[] = "DAYOFYEAR( $column ) $compare $value";
742 if ( isset( $query['day'] ) && $value = $this->build_value( $compare, $query['day'] ) )
743 $where_parts[] = "DAYOFMONTH( $column ) $compare $value";
745 if ( isset( $query['dayofweek'] ) && $value = $this->build_value( $compare, $query['dayofweek'] ) )
746 $where_parts[] = "DAYOFWEEK( $column ) $compare $value";
748 if ( isset( $query['dayofweek_iso'] ) && $value = $this->build_value( $compare, $query['dayofweek_iso'] ) )
749 $where_parts[] = "WEEKDAY( $column ) + 1 $compare $value";
751 if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
753 foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
754 if ( ! isset( $query[ $unit ] ) ) {
755 $query[ $unit ] = null;
759 if ( $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ) ) {
760 $where_parts[] = $time_query;
765 * Return an array of 'join' and 'where' for compatibility
766 * with other query classes.
769 'where' => $where_parts,
775 * Builds and validates a value string based on the comparison operator.
780 * @param string $compare The compare operator to use
781 * @param string|array $value The value
782 * @return string|false|int The value to be used in SQL or false on error.
784 public function build_value( $compare, $value ) {
785 if ( ! isset( $value ) )
788 switch ( $compare ) {
791 $value = (array) $value;
793 // Remove non-numeric values.
794 $value = array_filter( $value, 'is_numeric' );
796 if ( empty( $value ) ) {
800 return '(' . implode( ',', array_map( 'intval', $value ) ) . ')';
804 if ( ! is_array( $value ) || 2 != count( $value ) ) {
805 $value = array( $value, $value );
807 $value = array_values( $value );
810 // If either value is non-numeric, bail.
811 foreach ( $value as $v ) {
812 if ( ! is_numeric( $v ) ) {
817 $value = array_map( 'intval', $value );
819 return $value[0] . ' AND ' . $value[1];
822 if ( ! is_numeric( $value ) ) {
831 * Builds a MySQL format date/time based on some query parameters.
833 * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
834 * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
835 * pass a string that that will be run through strtotime().
840 * @param string|array $datetime An array of parameters or a strotime() string
841 * @param bool $default_to_max Whether to round up incomplete dates. Supported by values
842 * of $datetime that are arrays, or string values that are a
843 * subset of MySQL date format ('Y', 'Y-m', 'Y-m-d', 'Y-m-d H:i').
845 * @return string|false A MySQL format date/time or false on failure
847 public function build_mysql_datetime( $datetime, $default_to_max = false ) {
848 $now = current_time( 'timestamp' );
850 if ( ! is_array( $datetime ) ) {
853 * Try to parse some common date formats, so we can detect
854 * the level of precision and support the 'inclusive' parameter.
856 if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) {
859 'year' => intval( $matches[1] ),
862 } else if ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) {
865 'year' => intval( $matches[1] ),
866 'month' => intval( $matches[2] ),
869 } else if ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) {
872 'year' => intval( $matches[1] ),
873 'month' => intval( $matches[2] ),
874 'day' => intval( $matches[3] ),
877 } else if ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) {
880 'year' => intval( $matches[1] ),
881 'month' => intval( $matches[2] ),
882 'day' => intval( $matches[3] ),
883 'hour' => intval( $matches[4] ),
884 'minute' => intval( $matches[5] ),
888 // If no match is found, we don't support default_to_max.
889 if ( ! is_array( $datetime ) ) {
890 // @todo Timezone issues here possibly
891 return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
895 $datetime = array_map( 'absint', $datetime );
897 if ( ! isset( $datetime['year'] ) )
898 $datetime['year'] = gmdate( 'Y', $now );
900 if ( ! isset( $datetime['month'] ) )
901 $datetime['month'] = ( $default_to_max ) ? 12 : 1;
903 if ( ! isset( $datetime['day'] ) )
904 $datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
906 if ( ! isset( $datetime['hour'] ) )
907 $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
909 if ( ! isset( $datetime['minute'] ) )
910 $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
912 if ( ! isset( $datetime['second'] ) )
913 $datetime['second'] = ( $default_to_max ) ? 59 : 0;
915 return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
919 * Builds a query string for comparing time values (hour, minute, second).
921 * If just hour, minute, or second is set than a normal comparison will be done.
922 * However if multiple values are passed, a pseudo-decimal time will be created
923 * in order to be able to accurately compare against.
928 * @param string $column The column to query against. Needs to be pre-validated!
929 * @param string $compare The comparison operator. Needs to be pre-validated!
930 * @param int|null $hour Optional. An hour value (0-23).
931 * @param int|null $minute Optional. A minute value (0-59).
932 * @param int|null $second Optional. A second value (0-59).
933 * @return string|false A query part or false on failure.
935 public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
938 // Have to have at least one
939 if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) )
942 // Complex combined queries aren't supported for multi-value queries
943 if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
946 if ( isset( $hour ) && false !== ( $value = $this->build_value( $compare, $hour ) ) )
947 $return[] = "HOUR( $column ) $compare $value";
949 if ( isset( $minute ) && false !== ( $value = $this->build_value( $compare, $minute ) ) )
950 $return[] = "MINUTE( $column ) $compare $value";
952 if ( isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) )
953 $return[] = "SECOND( $column ) $compare $value";
955 return implode( ' AND ', $return );
958 // Cases where just one unit is set
959 if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $hour ) ) ) {
960 return "HOUR( $column ) $compare $value";
961 } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $minute ) ) ) {
962 return "MINUTE( $column ) $compare $value";
963 } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) ) {
964 return "SECOND( $column ) $compare $value";
967 // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
968 if ( ! isset( $minute ) )
971 $format = $time = '';
976 $time .= sprintf( '%02d', $hour ) . '.';
984 $time .= sprintf( '%02d', $minute );
986 if ( isset( $second ) ) {
988 $time .= sprintf( '%02d', $second );
991 return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );