Meta Query for specific months
-
22-04-2021 - |
Pergunta
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);
Solução
You 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'
);
Outras dicas
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 );
Licenciado em: CC-BY-SA com atribuição
Não afiliado a wordpress.stackexchange