On October 24, 2013,
WordPress
Version
3.7
, named for Count Basie, was released. It has some cool new features and one of those is that, developers can now query for posts within a date range, or that are older than or newer than a specific point in time using
date_query
.
For example, to get posts dated
December 12, 2012
, we can write the query like this:
$query = new WP_Query( 'year=2012&monthnum=12&day=12' );
Or using
date_query
, we can write:
$args = array(
'date_query' => array(
array(
'year' => 2012,
'month' => 12,
'day' => 12,
),
),
);
$query = new WP_Query( $args );
To get posts for today, we can write:
$today = getdate();
$query = new WP_Query( 'year=' . $today["year"] . '&monthnum=' . $today["mon"] . '&day=' . $today["mday"] );
Or using
date_query
, we can write:
$today = getdate();
$args = array(
'date_query' => array(
array(
'year' => $today["year"],
'month' => $today["mon"],
'day' => $today["mday"],
),
),
);
$query = new WP_Query( $args );
To get posts for this week, we can write:
$week = date('W');
$year = date('Y');
$query = new WP_Query( 'year=' . $year . '&w=' . $week );
Or using
date_query
, we can write:
$args = array(
'date_query' => array(
array(
'year' => date('Y'),
'week' => date('W'),
),
),
);
$query = new WP_Query( $args );
To get posts between
9am
to
5pm
on specific weekdays using
date_query
, we can write:
$args = array(
'date_query' => array(
array(
'hour' => 9,
'compare' => '>=',
),
array(
'hour' => 17,
'compare' => '<=',
),
array(
'dayofweek' => array( 2, 6 ),
'compare' => 'BETWEEN',
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
To get posts from
January 1st
to
February 28th
using
date_query
, we can write:
$args = array(
'date_query' => array(
array(
'after' => 'January 1st, 2013',
'before' => array(
'year' => 2013,
'month' => 2,
'day' => 28,
),
'inclusive' => true,
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
Another amaging
date_query
to return posts made over a year ago but modified in the past month (this is really cool), we can write:
$args = array(
'date_query' => array(
array(
'column' => 'post_date_gmt',
'before' => '1 year ago',
),
array(
'column' => 'post_modified_gmt',
'after' => '1 month ago',
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
It also works for comments, for example, to get all comments from post ID 10 that are within the past week, we can write:
$comments = get_comments( array(
'post_ID' => 10,
'date_query' => array(
array(
'after' => '1 week ago',
),
),
) );
This is really cool and this patch made by
Alex Mills
(AKA)
Viper007Bond on internet (also wrote many WordPress Plugins including
SyntaxHighlighter Evolved, that I'm currently using on my blog), so credit goes to him. Read more on
Codex about
date_query
and also learn more about new features of
WordPress Version-3.7.