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 ) ) {
309 * If a year exists in the date query, we can use it to get the days.
310 * If multiple years are provided (as in a BETWEEN), use the first one.
312 if ( is_array( $date_query['year'] ) ) {
313 $_year = reset( $date_query['year'] );
315 $_year = $date_query['year'];
318 $max_days_of_year = date( 'z', mktime( 0, 0, 0, 12, 31, $_year ) ) + 1;
320 // otherwise we use the max of 366 (leap-year)
321 $max_days_of_year = 366;
324 $min_max_checks['dayofyear'] = array(
326 'max' => $max_days_of_year
330 $min_max_checks['dayofweek'] = array(
336 $min_max_checks['dayofweek_iso'] = array(
342 $min_max_checks['month'] = array(
348 if ( isset( $_year ) ) {
349 // If we have a specific year, use it to calculate number of weeks.
350 $date = new DateTime();
351 $date->setISODate( $_year, 53 );
352 $week_count = $date->format( "W" ) === "53" ? 53 : 52;
355 // Otherwise set the week-count to a maximum of 53.
359 $min_max_checks['week'] = array(
365 $min_max_checks['day'] = array(
371 $min_max_checks['hour'] = array(
377 $min_max_checks['minute'] = array(
382 // Seconds per minute.
383 $min_max_checks['second'] = array(
388 // Concatenate and throw a notice for each invalid value.
389 foreach ( $min_max_checks as $key => $check ) {
390 if ( ! array_key_exists( $key, $date_query ) ) {
394 // Throw a notice for each failing value.
396 foreach ( (array) $date_query[ $key ] as $_value ) {
397 $is_between = $_value >= $check['min'] && $_value <= $check['max'];
399 if ( ! is_numeric( $_value ) || ! $is_between ) {
401 /* translators: Date query invalid date message: 1: invalid value, 2: type of value, 3: minimum valid value, 4: maximum valid value */
402 __( 'Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.' ),
403 '<code>' . esc_html( $_value ) . '</code>',
404 '<code>' . esc_html( $key ) . '</code>',
405 '<code>' . esc_html( $check['min'] ) . '</code>',
406 '<code>' . esc_html( $check['max'] ) . '</code>'
409 _doing_it_wrong( __CLASS__, $error, '4.1.0' );
416 // If we already have invalid date messages, don't bother running through checkdate().
421 $day_month_year_error_msg = '';
423 $day_exists = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] );
424 $month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] );
425 $year_exists = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] );
427 if ( $day_exists && $month_exists && $year_exists ) {
428 // 1. Checking day, month, year combination.
429 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'] ) ) ) {
430 /* translators: 1: year, 2: month, 3: day of month */
431 $day_month_year_error_msg = sprintf(
432 __( 'The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.' ),
433 '<code>' . esc_html( $date_query['year'] ) . '</code>',
434 '<code>' . esc_html( $date_query['month'] ) . '</code>',
435 '<code>' . esc_html( $date_query['day'] ) . '</code>'
441 } else if ( $day_exists && $month_exists ) {
443 * 2. checking day, month combination
444 * We use 2012 because, as a leap year, it's the most permissive.
446 if ( ! wp_checkdate( $date_query['month'], $date_query['day'], 2012, sprintf( '2012-%s-%s', $date_query['month'], $date_query['day'] ) ) ) {
447 /* translators: 1: month, 2: day of month */
448 $day_month_year_error_msg = sprintf(
449 __( 'The following values do not describe a valid date: month %1$s, day %2$s.' ),
450 '<code>' . esc_html( $date_query['month'] ) . '</code>',
451 '<code>' . esc_html( $date_query['day'] ) . '</code>'
458 if ( ! empty( $day_month_year_error_msg ) ) {
459 _doing_it_wrong( __CLASS__, $day_month_year_error_msg, '4.1.0' );
466 * Validates a column name parameter.
468 * Column names without a table prefix (like 'post_date') are checked against a whitelist of
469 * known tables, and then, if found, have a table prefix (such as 'wp_posts.') prepended.
470 * Prefixed column names (such as 'wp_posts.post_date') bypass this whitelist check,
471 * and are only sanitized to remove illegal characters.
476 * @param string $column The user-supplied column name.
477 * @return string A validated column name value.
479 public function validate_column( $column ) {
482 $valid_columns = array(
483 'post_date', 'post_date_gmt', 'post_modified',
484 'post_modified_gmt', 'comment_date', 'comment_date_gmt',
488 // Attempt to detect a table prefix.
489 if ( false === strpos( $column, '.' ) ) {
491 * Filter the list of valid date query columns.
494 * @since 4.1.0 Added 'user_registered' to the default recognized columns.
496 * @param array $valid_columns An array of valid date query columns. Defaults
497 * are 'post_date', 'post_date_gmt', 'post_modified',
498 * 'post_modified_gmt', 'comment_date', 'comment_date_gmt',
501 if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ) ) ) {
502 $column = 'post_date';
505 $known_columns = array(
506 $wpdb->posts => array(
512 $wpdb->comments => array(
516 $wpdb->users => array(
521 // If it's a known column name, add the appropriate table prefix.
522 foreach ( $known_columns as $table_name => $table_columns ) {
523 if ( in_array( $column, $table_columns ) ) {
524 $column = $table_name . '.' . $column;
531 // Remove unsafe characters.
532 return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column );
536 * Generate WHERE clause to be appended to a main query.
541 * @return string MySQL WHERE clause.
543 public function get_sql() {
544 $sql = $this->get_sql_clauses();
546 $where = $sql['where'];
549 * Filter the date query WHERE clause.
553 * @param string $where WHERE clause of the date query.
554 * @param WP_Date_Query $this The WP_Date_Query instance.
556 return apply_filters( 'get_date_sql', $where, $this );
560 * Generate SQL clauses to be appended to a main query.
562 * Called by the public {@see WP_Date_Query::get_sql()}, this method
563 * is abstracted out to maintain parity with the other Query classes.
569 * Array containing JOIN and WHERE SQL clauses to append to the main query.
571 * @type string $join SQL fragment to append to the main JOIN clause.
572 * @type string $where SQL fragment to append to the main WHERE clause.
575 protected function get_sql_clauses() {
576 $sql = $this->get_sql_for_query( $this->queries );
578 if ( ! empty( $sql['where'] ) ) {
579 $sql['where'] = ' AND ' . $sql['where'];
586 * Generate SQL clauses for a single query array.
588 * If nested subqueries are found, this method recurses the tree to
589 * produce the properly nested SQL.
594 * @param array $query Query to parse.
595 * @param int $depth Optional. Number of tree levels deep we currently are.
596 * Used to calculate indentation. Default 0.
598 * Array containing JOIN and WHERE SQL clauses to append to a single query array.
600 * @type string $join SQL fragment to append to the main JOIN clause.
601 * @type string $where SQL fragment to append to the main WHERE clause.
604 protected function get_sql_for_query( $query, $depth = 0 ) {
616 for ( $i = 0; $i < $depth; $i++ ) {
620 foreach ( $query as $key => $clause ) {
621 if ( 'relation' === $key ) {
622 $relation = $query['relation'];
623 } else if ( is_array( $clause ) ) {
625 // This is a first-order clause.
626 if ( $this->is_first_order_clause( $clause ) ) {
627 $clause_sql = $this->get_sql_for_clause( $clause, $query );
629 $where_count = count( $clause_sql['where'] );
630 if ( ! $where_count ) {
631 $sql_chunks['where'][] = '';
632 } else if ( 1 === $where_count ) {
633 $sql_chunks['where'][] = $clause_sql['where'][0];
635 $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
638 $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
639 // This is a subquery, so we recurse.
641 $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
643 $sql_chunks['where'][] = $clause_sql['where'];
644 $sql_chunks['join'][] = $clause_sql['join'];
649 // Filter to remove empties.
650 $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
651 $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
653 if ( empty( $relation ) ) {
657 // Filter duplicate JOIN clauses and combine into a single string.
658 if ( ! empty( $sql_chunks['join'] ) ) {
659 $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
662 // Generate a single WHERE clause with proper brackets and indentation.
663 if ( ! empty( $sql_chunks['where'] ) ) {
664 $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
671 * Turns a single date clause into pieces for a WHERE clause.
673 * A wrapper for get_sql_for_clause(), included here for backward
674 * compatibility while retaining the naming convention across Query classes.
679 * @param array $query Date query arguments.
681 * Array containing JOIN and WHERE SQL clauses to append to the main query.
683 * @type string $join SQL fragment to append to the main JOIN clause.
684 * @type string $where SQL fragment to append to the main WHERE clause.
687 protected function get_sql_for_subquery( $query ) {
688 return $this->get_sql_for_clause( $query, '' );
692 * Turns a first-order date query into SQL for a WHERE clause.
697 * @param array $query Date query clause.
698 * @param array $parent_query Parent query of the current date query.
700 * Array containing JOIN and WHERE SQL clauses to append to the main query.
702 * @type string $join SQL fragment to append to the main JOIN clause.
703 * @type string $where SQL fragment to append to the main WHERE clause.
706 protected function get_sql_for_clause( $query, $parent_query ) {
709 // The sub-parts of a $where part.
710 $where_parts = array();
712 $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
714 $column = $this->validate_column( $column );
716 $compare = $this->get_compare( $query );
718 $inclusive = ! empty( $query['inclusive'] );
720 // Assign greater- and less-than values.
730 if ( ! empty( $query['after'] ) )
731 $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) );
733 if ( ! empty( $query['before'] ) )
734 $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) );
736 // Specific value queries.
738 if ( isset( $query['year'] ) && $value = $this->build_value( $compare, $query['year'] ) )
739 $where_parts[] = "YEAR( $column ) $compare $value";
741 if ( isset( $query['month'] ) && $value = $this->build_value( $compare, $query['month'] ) )
742 $where_parts[] = "MONTH( $column ) $compare $value";
743 else if ( isset( $query['monthnum'] ) && $value = $this->build_value( $compare, $query['monthnum'] ) )
744 $where_parts[] = "MONTH( $column ) $compare $value";
746 if ( isset( $query['week'] ) && false !== ( $value = $this->build_value( $compare, $query['week'] ) ) )
747 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
748 else if ( isset( $query['w'] ) && false !== ( $value = $this->build_value( $compare, $query['w'] ) ) )
749 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
751 if ( isset( $query['dayofyear'] ) && $value = $this->build_value( $compare, $query['dayofyear'] ) )
752 $where_parts[] = "DAYOFYEAR( $column ) $compare $value";
754 if ( isset( $query['day'] ) && $value = $this->build_value( $compare, $query['day'] ) )
755 $where_parts[] = "DAYOFMONTH( $column ) $compare $value";
757 if ( isset( $query['dayofweek'] ) && $value = $this->build_value( $compare, $query['dayofweek'] ) )
758 $where_parts[] = "DAYOFWEEK( $column ) $compare $value";
760 if ( isset( $query['dayofweek_iso'] ) && $value = $this->build_value( $compare, $query['dayofweek_iso'] ) )
761 $where_parts[] = "WEEKDAY( $column ) + 1 $compare $value";
763 if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
765 foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
766 if ( ! isset( $query[ $unit ] ) ) {
767 $query[ $unit ] = null;
771 if ( $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ) ) {
772 $where_parts[] = $time_query;
777 * Return an array of 'join' and 'where' for compatibility
778 * with other query classes.
781 'where' => $where_parts,
787 * Builds and validates a value string based on the comparison operator.
792 * @param string $compare The compare operator to use
793 * @param string|array $value The value
794 * @return string|false|int The value to be used in SQL or false on error.
796 public function build_value( $compare, $value ) {
797 if ( ! isset( $value ) )
800 switch ( $compare ) {
803 $value = (array) $value;
805 // Remove non-numeric values.
806 $value = array_filter( $value, 'is_numeric' );
808 if ( empty( $value ) ) {
812 return '(' . implode( ',', array_map( 'intval', $value ) ) . ')';
816 if ( ! is_array( $value ) || 2 != count( $value ) ) {
817 $value = array( $value, $value );
819 $value = array_values( $value );
822 // If either value is non-numeric, bail.
823 foreach ( $value as $v ) {
824 if ( ! is_numeric( $v ) ) {
829 $value = array_map( 'intval', $value );
831 return $value[0] . ' AND ' . $value[1];
834 if ( ! is_numeric( $value ) ) {
843 * Builds a MySQL format date/time based on some query parameters.
845 * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
846 * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
847 * pass a string that that will be run through strtotime().
852 * @param string|array $datetime An array of parameters or a strotime() string
853 * @param bool $default_to_max Whether to round up incomplete dates. Supported by values
854 * of $datetime that are arrays, or string values that are a
855 * subset of MySQL date format ('Y', 'Y-m', 'Y-m-d', 'Y-m-d H:i').
857 * @return string|false A MySQL format date/time or false on failure
859 public function build_mysql_datetime( $datetime, $default_to_max = false ) {
860 $now = current_time( 'timestamp' );
862 if ( ! is_array( $datetime ) ) {
865 * Try to parse some common date formats, so we can detect
866 * the level of precision and support the 'inclusive' parameter.
868 if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) {
871 'year' => intval( $matches[1] ),
874 } else if ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) {
877 'year' => intval( $matches[1] ),
878 'month' => intval( $matches[2] ),
881 } else if ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) {
884 'year' => intval( $matches[1] ),
885 'month' => intval( $matches[2] ),
886 'day' => intval( $matches[3] ),
889 } else if ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) {
892 'year' => intval( $matches[1] ),
893 'month' => intval( $matches[2] ),
894 'day' => intval( $matches[3] ),
895 'hour' => intval( $matches[4] ),
896 'minute' => intval( $matches[5] ),
900 // If no match is found, we don't support default_to_max.
901 if ( ! is_array( $datetime ) ) {
902 // @todo Timezone issues here possibly
903 return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
907 $datetime = array_map( 'absint', $datetime );
909 if ( ! isset( $datetime['year'] ) )
910 $datetime['year'] = gmdate( 'Y', $now );
912 if ( ! isset( $datetime['month'] ) )
913 $datetime['month'] = ( $default_to_max ) ? 12 : 1;
915 if ( ! isset( $datetime['day'] ) )
916 $datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
918 if ( ! isset( $datetime['hour'] ) )
919 $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
921 if ( ! isset( $datetime['minute'] ) )
922 $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
924 if ( ! isset( $datetime['second'] ) )
925 $datetime['second'] = ( $default_to_max ) ? 59 : 0;
927 return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
931 * Builds a query string for comparing time values (hour, minute, second).
933 * If just hour, minute, or second is set than a normal comparison will be done.
934 * However if multiple values are passed, a pseudo-decimal time will be created
935 * in order to be able to accurately compare against.
940 * @param string $column The column to query against. Needs to be pre-validated!
941 * @param string $compare The comparison operator. Needs to be pre-validated!
942 * @param int|null $hour Optional. An hour value (0-23).
943 * @param int|null $minute Optional. A minute value (0-59).
944 * @param int|null $second Optional. A second value (0-59).
945 * @return string|false A query part or false on failure.
947 public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
950 // Have to have at least one
951 if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) )
954 // Complex combined queries aren't supported for multi-value queries
955 if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
958 if ( isset( $hour ) && false !== ( $value = $this->build_value( $compare, $hour ) ) )
959 $return[] = "HOUR( $column ) $compare $value";
961 if ( isset( $minute ) && false !== ( $value = $this->build_value( $compare, $minute ) ) )
962 $return[] = "MINUTE( $column ) $compare $value";
964 if ( isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) )
965 $return[] = "SECOND( $column ) $compare $value";
967 return implode( ' AND ', $return );
970 // Cases where just one unit is set
971 if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $hour ) ) ) {
972 return "HOUR( $column ) $compare $value";
973 } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $minute ) ) ) {
974 return "MINUTE( $column ) $compare $value";
975 } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) ) {
976 return "SECOND( $column ) $compare $value";
979 // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
980 if ( ! isset( $minute ) )
983 $format = $time = '';
988 $time .= sprintf( '%02d', $hour ) . '.';
996 $time .= sprintf( '%02d', $minute );
998 if ( isset( $second ) ) {
1000 $time .= sprintf( '%02d', $second );
1003 return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );