It's a little complicated, but we can do this by directly modifying the query with a filter on posts_where
.
We'll start with a query for posts with a meta value of today's date, this is assuming a date format of yyyy-mm-dd
:
$date_today = date('Y-m-d');
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'died_date',
'value' => $date_today,
'compare' => '=',
'type' => 'DATE'
)
)
);
$results = new WP_Query( $args );
If we look at the WHERE
clause of this query, we'll see the relevant bit:
AND ( (wp_postmeta.meta_key = 'died_date'
AND CAST(wp_postmeta.meta_value AS DATE) = '2013-02-14') )
To get this to work, we want to modify the last line to use MySQL's DAYOFYEAR in the comparison.
So here's our filter:
function wpa86916_filter_where( $where ){
global $wpdb;
$date_today = date('Y-m-d');
$parts = explode( 'AND CAST', $where );
$new_where = " AND DAYOFYEAR( CAST( $wpdb->postmeta.meta_value AS DATE ) ) = DAYOFYEAR( '$date_today' ) ) )";
$where = $parts[0] . $new_where;
remove_filter( 'posts_where', __FUNCTION__ );
return $where;
}
If we back up to our original query, we can now add this filter before the query, and we should get all posts with matching day of year, regardless of year:
add_filter( 'posts_where', 'wpa86916_filter_where' );
$results = new WP_Query( $args );
As for your question regarding extraction of the year from a date, we can use PHP's date
and strtotime
to do any date extraction and conversion:
$date = '2013-02-14';
echo date( 'Y', strtotime( $date ) );
// prints '2013'