admin管理员组文章数量:1310297
I have a custom field which stores a date in a timestamp. I want to run a query that display posts based on the month, for example all entries from March, the specific day or year doesn't matter. I'm guessing i need to use the DATE or the DATETIME type for the meta query, but i don't know how to proceed:
if ($_GET['month']) {
$meta_query[] = array(
'key' => 'event_start_date',
'value' => $_GET['month']
);
}
$args = array(
'post_type' => 'event',
'paged' => $paged,
'posts_per_page' => -1,
'tax_query' => $cleanArray,
'meta_key' => 'event_start_date',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query'=> $meta_query
);
$events = new WP_Query($args);
I have a custom field which stores a date in a timestamp. I want to run a query that display posts based on the month, for example all entries from March, the specific day or year doesn't matter. I'm guessing i need to use the DATE or the DATETIME type for the meta query, but i don't know how to proceed:
if ($_GET['month']) {
$meta_query[] = array(
'key' => 'event_start_date',
'value' => $_GET['month']
);
}
$args = array(
'post_type' => 'event',
'paged' => $paged,
'posts_per_page' => -1,
'tax_query' => $cleanArray,
'meta_key' => 'event_start_date',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query'=> $meta_query
);
$events = new WP_Query($args);
Share
Improve this question
asked Oct 14, 2013 at 16:02
passatgtpassatgt
3,4016 gold badges32 silver badges37 bronze badges
1
|
3 Answers
Reset to default 5You need the 2 digit month number that you want to query on and then use the code below. This should be easy with php (for example, see this post). In the code below $month
is the number of the month in a 2 digit format, eg March would be 03.
$start_date = date('Y'.$month.'01'); // First day of the month
$end_date = date('Y'.$month.'t'); // 't' gets the last day of the month
$meta_query = array(
'key' => 'event_start_date',
'value' => array($start_date, $end_date),
'compare' => 'BETWEEN',
'type' => 'DATE'
);
For Date Time just add eg. 00:00:00 - 23:00:00
$month = $_GET['month'];
$start_date = date( 'Y-' . $month . '-01 00:00:00' );
$end_date = date( 'Y-' . $month . '-t 23:00:00', strtotime( $start_date ) );
$meta_query = array(
'key' => 'event_start_date',
'value' => array($start_date, $end_date),
'compare' => 'BETWEEN',
'type' => 'DATETIME'
);
WordPress 3.7 introduced the date_query
to display posts by month:
$args = array(
'date_query' => array(
array(
'month' => $month
)
)
);
$query = new WP_Query( $args );
本文标签: Meta Query for specific months
版权声明:本文标题:Meta Query for specific months 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741827516a2399732.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
WP_Query
, you'll need a filter onposts_where
to query on just the month using MySQL's month function. – Milo Commented Oct 14, 2013 at 16:10