3 * WP_Date_Query will generate a MySQL WHERE clause for the specified date-based parameters.
5 * Initialize the class by passing an array of arrays of parameters.
7 * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page.
13 * List of date queries.
19 public $queries = array();
22 * The relation between the queries. Can be either 'AND' or 'OR' and can be changed via the query arguments.
28 public $relation = 'AND';
31 * The column to query against. Can be changed via the query arguments.
37 public $column = 'post_date';
40 * The value comparison operator. Can be changed via the query arguments.
46 public $compare = '=';
52 * @since 4.0.0 The $inclusive logic was updated to include all times within the date range.
54 * @param array $date_query {
55 * One or more associative arrays of date query parameters.
58 * @type string $column Optional. The column to query against. If undefined, inherits the value of
59 * the $default_column parameter. Default 'post_date'. Accepts 'post_date',
60 * 'post_date_gmt', 'post_modified','post_modified_gmt', 'comment_date',
62 * @type string $compare Optional. The comparison operator.
63 * Default '='. Accepts '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN',
64 * 'BETWEEN', 'NOT BETWEEN'.
65 * @type string $relation Optional. The boolean relationship between the date queryies.
66 * Default 'OR'. Accepts 'OR', 'AND'.
68 * @type string|array $before Optional. Date to retrieve posts before. Accepts strtotime()-compatible
69 * string, or array of 'year', 'month', 'day' values. {
71 * @type string $year The four-digit year. Default empty. Accepts any four-digit year.
72 * @type string $month Optional when passing array.The month of the year.
73 * Default (string:empty)|(array:1). Accepts numbers 1-12.
74 * @type string $day Optional when passing array.The day of the month.
75 * Default (string:empty)|(array:1). Accepts numbers 1-31.
77 * @type string|array $after Optional. Date to retrieve posts after. Accepts strtotime()-compatible
78 * string, or array of 'year', 'month', 'day' values. {
80 * @type string $year The four-digit year. Default empty. Accepts any four-digit year.
81 * @type string $month Optional when passing array.The month of the year.
82 * Default (string:empty)|(array:12). Accepts numbers 1-12.
83 * @type string $day Optional when passing array.The day of the month.
84 * Default (string:empty)|(array:last day of month). Accepts numbers 1-31.
86 * @type string $column Optional. Used to add a clause comparing a column other than the column
87 * specified in the top-level $column parameter. Default is the value
88 * of top-level $column. Accepts 'post_date', 'post_date_gmt',
89 * 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt'.
90 * @type string $compare Optional. The comparison operator. Default '='. Accepts '=', '!=',
91 * '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
92 * @type bool $inclusive Optional. Include results from dates specified in 'before' or 'after'.
94 * @type int $year Optional. The four-digit year number. Default empty. Accepts any
96 * @type int $month Optional. The two-digit month number. Default empty. Accepts numbers 1-12.
97 * @type int $week Optional. The week number of the year. Default empty. Accepts numbers 0-53.
98 * @type int $dayofyear Optional. The day number of the year. Default empty. Accepts numbers 1-366.
99 * @type int $day Optional. The day of the month. Default empty. Accepts numbers 1-31.
100 * @type int $dayofweek Optional. The day number of the week. Default empty. Accepts numbers 1-7.
101 * @type int $hour Optional. The hour of the day. Default empty. Accepts numbers 0-23.
102 * @type int $minute Optional. The minute of the hour. Default empty. Accepts numbers 0-60.
103 * @type int $second Optional. The second of the minute. Default empty. Accepts numbers 0-60.
107 * @param array $default_column Optional. Default column to query against. Default 'post_date'.
108 * Accepts 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt',
109 * 'comment_date', 'comment_date_gmt'.
111 public function __construct( $date_query, $default_column = 'post_date' ) {
112 if ( empty( $date_query ) || ! is_array( $date_query ) )
115 if ( isset( $date_query['relation'] ) && strtoupper( $date_query['relation'] ) == 'OR' )
116 $this->relation = 'OR';
118 $this->relation = 'AND';
120 if ( ! empty( $date_query['column'] ) )
121 $this->column = esc_sql( $date_query['column'] );
123 $this->column = esc_sql( $default_column );
125 $this->column = $this->validate_column( $this->column );
127 $this->compare = $this->get_compare( $date_query );
129 // If an array of arrays wasn't passed, fix it
130 if ( ! isset( $date_query[0] ) )
131 $date_query = array( $date_query );
133 $this->queries = array();
134 foreach ( $date_query as $key => $query ) {
135 if ( ! is_array( $query ) )
138 $this->queries[$key] = $query;
143 * Determines and validates what comparison operator to use.
148 * @param array $query A date query or a date subquery
149 * @return string The comparison operator
151 public function get_compare( $query ) {
152 if ( ! empty( $query['compare'] ) && in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
153 return strtoupper( $query['compare'] );
155 return $this->compare;
159 * Validates a column name parameter.
164 * @param string $column The user-supplied column name.
165 * @return string A validated column name value.
167 public function validate_column( $column ) {
168 $valid_columns = array(
169 'post_date', 'post_date_gmt', 'post_modified',
170 'post_modified_gmt', 'comment_date', 'comment_date_gmt'
173 * Filter the list of valid date query columns.
177 * @param array $valid_columns An array of valid date query columns. Defaults are 'post_date', 'post_date_gmt',
178 * 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt'
180 if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ) ) )
181 $column = 'post_date';
187 * Turns an array of date query parameters into a MySQL string.
192 * @return string MySQL WHERE parameters
194 public function get_sql() {
195 // The parts of the final query
198 foreach ( $this->queries as $key => $query ) {
199 $where_parts = $this->get_sql_for_subquery( $query );
200 if ( $where_parts ) {
201 // Combine the parts of this subquery into a single string
202 $where[ $key ] = '( ' . implode( ' AND ', $where_parts ) . ' )';
206 // Combine the subquery strings into a single string
208 $where = ' AND ( ' . implode( " {$this->relation} ", $where ) . ' )';
213 * Filter the date query WHERE clause.
217 * @param string $where WHERE clause of the date query.
218 * @param WP_Date_Query $this The WP_Date_Query instance.
220 return apply_filters( 'get_date_sql', $where, $this );
224 * Turns a single date subquery into pieces for a WHERE clause.
229 protected function get_sql_for_subquery( $query ) {
232 // The sub-parts of a $where part
233 $where_parts = array();
235 $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
237 $column = $this->validate_column( $column );
239 $compare = $this->get_compare( $query );
241 $inclusive = ! empty( $query['inclusive'] );
243 // Assign greater- and less-than values.
253 if ( ! empty( $query['after'] ) )
254 $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) );
256 if ( ! empty( $query['before'] ) )
257 $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) );
259 // Specific value queries
261 if ( isset( $query['year'] ) && $value = $this->build_value( $compare, $query['year'] ) )
262 $where_parts[] = "YEAR( $column ) $compare $value";
264 if ( isset( $query['month'] ) && $value = $this->build_value( $compare, $query['month'] ) )
265 $where_parts[] = "MONTH( $column ) $compare $value";
266 else if ( isset( $query['monthnum'] ) && $value = $this->build_value( $compare, $query['monthnum'] ) )
267 $where_parts[] = "MONTH( $column ) $compare $value";
269 if ( isset( $query['week'] ) && false !== ( $value = $this->build_value( $compare, $query['week'] ) ) )
270 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
271 else if ( isset( $query['w'] ) && false !== ( $value = $this->build_value( $compare, $query['w'] ) ) )
272 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
274 if ( isset( $query['dayofyear'] ) && $value = $this->build_value( $compare, $query['dayofyear'] ) )
275 $where_parts[] = "DAYOFYEAR( $column ) $compare $value";
277 if ( isset( $query['day'] ) && $value = $this->build_value( $compare, $query['day'] ) )
278 $where_parts[] = "DAYOFMONTH( $column ) $compare $value";
280 if ( isset( $query['dayofweek'] ) && $value = $this->build_value( $compare, $query['dayofweek'] ) )
281 $where_parts[] = "DAYOFWEEK( $column ) $compare $value";
283 if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
285 foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
286 if ( ! isset( $query[$unit] ) ) {
287 $query[$unit] = null;
291 if ( $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ) ) {
292 $where_parts[] = $time_query;
300 * Builds and validates a value string based on the comparison operator.
305 * @param string $compare The compare operator to use
306 * @param string|array $value The value
307 * @return string|int|false The value to be used in SQL or false on error.
309 public function build_value( $compare, $value ) {
310 if ( ! isset( $value ) )
313 switch ( $compare ) {
316 return '(' . implode( ',', array_map( 'intval', (array) $value ) ) . ')';
320 if ( ! is_array( $value ) || 2 != count( $value ) || ! isset( $value[0] ) || ! isset( $value[1] ) )
321 $value = array( $value, $value );
323 $value = array_map( 'intval', $value );
325 return $value[0] . ' AND ' . $value[1];
333 * Builds a MySQL format date/time based on some query parameters.
335 * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
336 * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
337 * pass a string that that will be run through strtotime().
342 * @param string|array $datetime An array of parameters or a strotime() string
343 * @param string $default_to Controls what values default to if they are missing from $datetime. Pass "min" or "max".
344 * @return string|false A MySQL format date/time or false on failure
346 public function build_mysql_datetime( $datetime, $default_to_max = false ) {
347 $now = current_time( 'timestamp' );
349 if ( ! is_array( $datetime ) ) {
350 // @todo Timezone issues here possibly
351 return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
354 $datetime = array_map( 'absint', $datetime );
356 if ( ! isset( $datetime['year'] ) )
357 $datetime['year'] = gmdate( 'Y', $now );
359 if ( ! isset( $datetime['month'] ) )
360 $datetime['month'] = ( $default_to_max ) ? 12 : 1;
362 if ( ! isset( $datetime['day'] ) )
363 $datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
365 if ( ! isset( $datetime['hour'] ) )
366 $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
368 if ( ! isset( $datetime['minute'] ) )
369 $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
371 if ( ! isset( $datetime['second'] ) )
372 $datetime['second'] = ( $default_to_max ) ? 59 : 0;
374 return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
378 * Builds a query string for comparing time values (hour, minute, second).
380 * If just hour, minute, or second is set than a normal comparison will be done.
381 * However if multiple values are passed, a pseudo-decimal time will be created
382 * in order to be able to accurately compare against.
387 * @param string $column The column to query against. Needs to be pre-validated!
388 * @param string $compare The comparison operator. Needs to be pre-validated!
389 * @param int|null $hour Optional. An hour value (0-23).
390 * @param int|null $minute Optional. A minute value (0-59).
391 * @param int|null $second Optional. A second value (0-59).
392 * @return string|false A query part or false on failure.
394 public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
397 // Have to have at least one
398 if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) )
401 // Complex combined queries aren't supported for multi-value queries
402 if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
405 if ( isset( $hour ) && false !== ( $value = $this->build_value( $compare, $hour ) ) )
406 $return[] = "HOUR( $column ) $compare $value";
408 if ( isset( $minute ) && false !== ( $value = $this->build_value( $compare, $minute ) ) )
409 $return[] = "MINUTE( $column ) $compare $value";
411 if ( isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) )
412 $return[] = "SECOND( $column ) $compare $value";
414 return implode( ' AND ', $return );
417 // Cases where just one unit is set
418 if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $hour ) ) ) {
419 return "HOUR( $column ) $compare $value";
420 } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $minute ) ) ) {
421 return "MINUTE( $column ) $compare $value";
422 } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) ) {
423 return "SECOND( $column ) $compare $value";
426 // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
427 if ( ! isset( $minute ) )
430 $format = $time = '';
435 $time .= sprintf( '%02d', $hour ) . '.';
443 $time .= sprintf( '%02d', $minute );
445 if ( isset( $second ) ) {
447 $time .= sprintf( '%02d', $second );
450 return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );