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 = '=';
51 * @param array $date_query {
52 * One or more associative arrays of date query parameters.
55 * @type string $column Optional. The column to query against. If undefined, inherits the value of
56 * the $default_column parameter. Default 'post_date'. Accepts 'post_date',
57 * 'post_date_gmt', 'post_modified','post_modified_gmt', 'comment_date',
59 * @type string $compare Optional. The comparison operator.
60 * Default '='. Accepts '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN',
61 * 'BETWEEN', 'NOT BETWEEN'.
62 * @type string $relation Optional. The boolean relationship between the date queryies.
63 * Default 'OR'. Accepts 'OR', 'AND'.
65 * @type string|array $before Optional. Date to retrieve posts before. Accepts strtotime()-compatible
66 * string, or array of 'year', 'month', 'day' values. {
68 * @type string $year The four-digit year. Default empty. Accepts any four-digit year.
69 * @type string $month Optional when passing array.The month of the year.
70 * Default (string:empty)|(array:1). Accepts numbers 1-12.
71 * @type string $day Optional when passing array.The day of the month.
72 * Default (string:empty)|(array:1). Accepts numbers 1-31.
74 * @type string|array $after Optional. Date to retrieve posts after. Accepts strtotime()-compatible
75 * string, or array of 'year', 'month', 'day' values. {
77 * @type string $year The four-digit year. Default empty. Accepts any four-digit year.
78 * @type string $month Optional when passing array.The month of the year.
79 * Default (string:empty)|(array:12). Accepts numbers 1-12.
80 * @type string $day Optional when passing array.The day of the month.
81 * Default (string:empty)|(array:last day of month). Accepts numbers 1-31.
83 * @type string $column Optional. Used to add a clause comparing a column other than the column
84 * specified in the top-level $column paramater. Default is the value
85 * of top-level $column. Accepts 'post_date', 'post_date_gmt',
86 * 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt'.
87 * @type string $compare Optional. The comparison operator. Default '='. Accepts '=', '!=',
88 * '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
89 * @type bool $inclusive Optional. Include results from dates specified in 'before' or 'after'.
91 * @type int $year Optional. The four-digit year number. Default empty. Accepts any
93 * @type int $month Optional. The two-digit month number. Default empty. Accepts numbers 1-12.
94 * @type int $week Optional. The week number of the year. Default empty. Accepts numbers 0-53.
95 * @type int $dayofyear Optional. The day number of the year. Default empty. Accepts numbers 1-366.
96 * @type int $day Optional. The day of the month. Default empty. Accepts numbers 1-31.
97 * @type int $dayofweek Optional. The day number of the week. Default empty. Accepts numbers 1-7.
98 * @type int $hour Optional. The hour of the day. Default empty. Accepts numbers 0-23.
99 * @type int $minute Optional. The minute of the hour. Default empty. Accepts numbers 0-60.
100 * @type int $second Optional. The second of the minute. Default empty. Accepts numbers 0-60.
104 * @param array $default_column Optional. Default column to query against. Default 'post_date'.
105 * Accepts 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt',
106 * 'comment_date', 'comment_date_gmt'.
108 function __construct( $date_query, $default_column = 'post_date' ) {
109 if ( empty( $date_query ) || ! is_array( $date_query ) )
112 if ( isset( $date_query['relation'] ) && strtoupper( $date_query['relation'] ) == 'OR' )
113 $this->relation = 'OR';
115 $this->relation = 'AND';
117 if ( ! empty( $date_query['column'] ) )
118 $this->column = esc_sql( $date_query['column'] );
120 $this->column = esc_sql( $default_column );
122 $this->column = $this->validate_column( $this->column );
124 $this->compare = $this->get_compare( $date_query );
126 // If an array of arrays wasn't passed, fix it
127 if ( ! isset( $date_query[0] ) )
128 $date_query = array( $date_query );
130 $this->queries = array();
131 foreach ( $date_query as $key => $query ) {
132 if ( ! is_array( $query ) )
135 $this->queries[$key] = $query;
140 * Determines and validates what comparison operator to use.
145 * @param array $query A date query or a date subquery
146 * @return string The comparison operator
148 public function get_compare( $query ) {
149 if ( ! empty( $query['compare'] ) && in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
150 return strtoupper( $query['compare'] );
152 return $this->compare;
156 * Validates a column name parameter.
161 * @param string $column The user-supplied column name.
162 * @return string A validated column name value.
164 public function validate_column( $column ) {
165 $valid_columns = array(
166 'post_date', 'post_date_gmt', 'post_modified',
167 'post_modified_gmt', 'comment_date', 'comment_date_gmt'
170 * Filter the list of valid date query columns.
174 * @param array $valid_columns An array of valid date query columns. Defaults are 'post_date', 'post_date_gmt',
175 * 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt'
177 if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ) ) )
178 $column = 'post_date';
184 * Turns an array of date query parameters into a MySQL string.
189 * @return string MySQL WHERE parameters
191 public function get_sql() {
192 // The parts of the final query
195 foreach ( $this->queries as $key => $query ) {
196 $where_parts = $this->get_sql_for_subquery( $query );
197 if ( $where_parts ) {
198 // Combine the parts of this subquery into a single string
199 $where[ $key ] = '( ' . implode( ' AND ', $where_parts ) . ' )';
203 // Combine the subquery strings into a single string
205 $where = ' AND ( ' . implode( " {$this->relation} ", $where ) . ' )';
210 * Filter the date query WHERE clause.
214 * @param string $where WHERE clause of the date query.
215 * @param WP_Date_Query $this The WP_Date_Query instance.
217 return apply_filters( 'get_date_sql', $where, $this );
221 * Turns a single date subquery into pieces for a WHERE clause.
226 protected function get_sql_for_subquery( $query ) {
229 // The sub-parts of a $where part
230 $where_parts = array();
232 $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
234 $column = $this->validate_column( $column );
236 $compare = $this->get_compare( $query );
240 if ( ! empty( $query['inclusive'] ) ) {
246 if ( ! empty( $query['after'] ) )
247 $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], true ) );
249 if ( ! empty( $query['before'] ) )
250 $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], false ) );
252 // Specific value queries
254 if ( isset( $query['year'] ) && $value = $this->build_value( $compare, $query['year'] ) )
255 $where_parts[] = "YEAR( $column ) $compare $value";
257 if ( isset( $query['month'] ) && $value = $this->build_value( $compare, $query['month'] ) )
258 $where_parts[] = "MONTH( $column ) $compare $value";
261 if ( isset( $query['monthnum'] ) && $value = $this->build_value( $compare, $query['monthnum'] ) )
262 $where_parts[] = "MONTH( $column ) $compare $value";
264 if ( isset( $query['week'] ) && false !== ( $value = $this->build_value( $compare, $query['week'] ) ) )
265 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
268 if ( isset( $query['w'] ) && false !== ( $value = $this->build_value( $compare, $query['w'] ) ) )
269 $where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
271 if ( isset( $query['dayofyear'] ) && $value = $this->build_value( $compare, $query['dayofyear'] ) )
272 $where_parts[] = "DAYOFYEAR( $column ) $compare $value";
274 if ( isset( $query['day'] ) && $value = $this->build_value( $compare, $query['day'] ) )
275 $where_parts[] = "DAYOFMONTH( $column ) $compare $value";
277 if ( isset( $query['dayofweek'] ) && $value = $this->build_value( $compare, $query['dayofweek'] ) )
278 $where_parts[] = "DAYOFWEEK( $column ) $compare $value";
280 if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
282 foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
283 if ( ! isset( $query[$unit] ) ) {
284 $query[$unit] = null;
288 if ( $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ) ) {
289 $where_parts[] = $time_query;
297 * Builds and validates a value string based on the comparison operator.
302 * @param string $compare The compare operator to use
303 * @param string|array $value The value
304 * @return string|int|false The value to be used in SQL or false on error.
306 public function build_value( $compare, $value ) {
307 if ( ! isset( $value ) )
310 switch ( $compare ) {
313 return '(' . implode( ',', array_map( 'intval', (array) $value ) ) . ')';
317 if ( ! is_array( $value ) || 2 != count( $value ) || ! isset( $value[0] ) || ! isset( $value[1] ) )
318 $value = array( $value, $value );
320 $value = array_map( 'intval', $value );
322 return $value[0] . ' AND ' . $value[1];
330 * Builds a MySQL format date/time based on some query parameters.
332 * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
333 * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
334 * pass a string that that will be run through strtotime().
339 * @param string|array $datetime An array of parameters or a strotime() string
340 * @param string $default_to Controls what values default to if they are missing from $datetime. Pass "min" or "max".
341 * @return string|false A MySQL format date/time or false on failure
343 public function build_mysql_datetime( $datetime, $default_to_max = false ) {
344 $now = current_time( 'timestamp' );
346 if ( ! is_array( $datetime ) ) {
347 // @todo Timezone issues here possibly
348 return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
351 $datetime = array_map( 'absint', $datetime );
353 if ( ! isset( $datetime['year'] ) )
354 $datetime['year'] = gmdate( 'Y', $now );
356 if ( ! isset( $datetime['month'] ) )
357 $datetime['month'] = ( $default_to_max ) ? 12 : 1;
359 if ( ! isset( $datetime['day'] ) )
360 $datetime['day'] = ( $default_to_max ) ? (int) date( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
362 if ( ! isset( $datetime['hour'] ) )
363 $datetime['hour'] = ( $default_to_max ) ? 23 : 0;
365 if ( ! isset( $datetime['minute'] ) )
366 $datetime['minute'] = ( $default_to_max ) ? 59 : 0;
368 if ( ! isset( $datetime['second'] ) )
369 $datetime['second'] = ( $default_to_max ) ? 59 : 0;
371 return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
375 * Builds a query string for comparing time values (hour, minute, second).
377 * If just hour, minute, or second is set than a normal comparison will be done.
378 * However if multiple values are passed, a pseudo-decimal time will be created
379 * in order to be able to accurately compare against.
384 * @param string $column The column to query against. Needs to be pre-validated!
385 * @param string $compare The comparison operator. Needs to be pre-validated!
386 * @param int|null $hour Optional. An hour value (0-23).
387 * @param int|null $minute Optional. A minute value (0-59).
388 * @param int|null $second Optional. A second value (0-59).
389 * @return string|false A query part or false on failure.
391 public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
394 // Have to have at least one
395 if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) )
398 // Complex combined queries aren't supported for multi-value queries
399 if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
402 if ( isset( $hour ) && false !== ( $value = $this->build_value( $compare, $hour ) ) )
403 $return[] = "HOUR( $column ) $compare $value";
405 if ( isset( $minute ) && false !== ( $value = $this->build_value( $compare, $minute ) ) )
406 $return[] = "MINUTE( $column ) $compare $value";
408 if ( isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) )
409 $return[] = "SECOND( $column ) $compare $value";
411 return implode( ' AND ', $return );
414 // Cases where just one unit is set
415 if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $hour ) ) ) {
416 return "HOUR( $column ) $compare $value";
417 } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_value( $compare, $minute ) ) ) {
418 return "MINUTE( $column ) $compare $value";
419 } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_value( $compare, $second ) ) ) {
420 return "SECOND( $column ) $compare $value";
423 // Single units were already handled. Since hour & second isn't allowed, minute must to be set.
424 if ( ! isset( $minute ) )
427 $format = $time = '';
432 $time .= sprintf( '%02d', $hour ) . '.';
440 $time .= sprintf( '%02d', $minute );
442 if ( isset( $second ) ) {
444 $time .= sprintf( '%02d', $second );
447 return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );