Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ivankravchenko/6322195 to your computer and use it in GitHub Desktop.

Select an option

Save ivankravchenko/6322195 to your computer and use it in GitHub Desktop.
Wordpress wp_query date range date_from date_to filter.
<?php
// https://gist.github.com/krava/6322195
// Wordpress wp_query date range date_from date_to filter.
add_filter('posts_where', 'wapp_filter_posts_where');
function wapp_filter_posts_where($where) {
global $wp_query;
if (isset($wp_query->query['date_from']) && isset($wp_query->query['date_to'])) {
$date_from = $wp_query->query['date_from'];
$date_to = $wp_query->query['date_to'];
$r = '/^\d{4}-\d{2}-\d{2}$/';
if (!(preg_match($r, $date_from) && preg_match($r, $date_to)))
die('invalid date format for date_from and date_to');
$where .= " AND post_date BETWEEN STR_TO_DATE('$date_from 00:00:00', '%Y-%m-%d %H:%i:%s') AND STR_TO_DATE('$date_to 23:59:59', '%Y-%m-%d %H:%i:%s')";
}
return $where;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment