qual è il modo corretto per confrontare le date in un WP query_posts meta_query
4 risposta
- voti
-
- 2011-03-07
Hofinito con quanto segue. Hoimpostato un campoevento-mesee confronto da lì.grazieper l'aiuto
<?php $event_query = new WP_Query( array( 'post_type' => 'event', // only query events 'meta_key' => 'event-month', // load up the event_date meta 'order_by' => 'event_date', 'order' => 'asc', // ascending, so earlier events first 'meta_query' => array( array( // restrict posts based on meta values 'key' => 'event-month', // which meta to query 'value' => date("n"), // value for comparison 'compare' => '=', // method of comparison 'type' => 'NUMERIC' // datatype, we don't want to compare the string values ) // meta_query is an array of query ites ) // end meta_query array ) // end array ); // close WP_Query constructor call ?> <?php while($event_query->have_posts()): $event_query->the_post(); //loop for events ?>
I wound up going with the following. I setup a event-momth field and comparing from there. thanks for the help
<?php $event_query = new WP_Query( array( 'post_type' => 'event', // only query events 'meta_key' => 'event-month', // load up the event_date meta 'order_by' => 'event_date', 'order' => 'asc', // ascending, so earlier events first 'meta_query' => array( array( // restrict posts based on meta values 'key' => 'event-month', // which meta to query 'value' => date("n"), // value for comparison 'compare' => '=', // method of comparison 'type' => 'NUMERIC' // datatype, we don't want to compare the string values ) // meta_query is an array of query ites ) // end meta_query array ) // end array ); // close WP_Query constructor call ?> <?php while($event_query->have_posts()): $event_query->the_post(); //loop for events ?>
-
- 2011-03-17
Hofinitoper lavorare sulla stessaidentica cosae questopost è statomolto utile. Ho utilizzatoi campipersonalizzatiedeccoil codice che ho utilizzatoper creare unelenco dituttiglieventi maggiori della data corrente. Notai filtriextrabasati sullatassonomia.
<?php // Let's get the data we need to loop through below $events = new WP_Query( array( 'post_type' => 'event', // Tell WordPress which post type we want 'orderby' => 'meta_value', // We want to organize the events by date 'meta_key' => 'event-start-date', // Grab the "start date" field created via "More Fields" plugin (stored in YYYY-MM-DD format) 'order' => 'ASC', // ASC is the other option 'posts_per_page' => '-1', // Let's show them all. 'meta_query' => array( // WordPress has all the results, now, return only the events after today's date array( 'key' => 'event-start-date', // Check the start date field 'value' => date("Y-m-d"), // Set today's date (note the similar format) 'compare' => '>=', // Return the ones greater than today's date 'type' => 'DATE' // Let WordPress know we're working with date ) ), 'tax_query' => array( // Return only concerts (event-types) and events where "songs-of-ascent" is performing array( 'taxonomy' => 'event-types', 'field' => 'slug', 'terms' => 'concert', ), array( 'taxonomy' => 'speakers', 'field' => 'slug', 'terms' => 'songs-of-ascent', ) ) ) ); ?>
I wound up working on the exact same thing and this post was very helpful. I used Custom Fields and here is the code that I used to create a list of all events greater than the current date. Note the extra taxonomy based filters.
<?php // Let's get the data we need to loop through below $events = new WP_Query( array( 'post_type' => 'event', // Tell WordPress which post type we want 'orderby' => 'meta_value', // We want to organize the events by date 'meta_key' => 'event-start-date', // Grab the "start date" field created via "More Fields" plugin (stored in YYYY-MM-DD format) 'order' => 'ASC', // ASC is the other option 'posts_per_page' => '-1', // Let's show them all. 'meta_query' => array( // WordPress has all the results, now, return only the events after today's date array( 'key' => 'event-start-date', // Check the start date field 'value' => date("Y-m-d"), // Set today's date (note the similar format) 'compare' => '>=', // Return the ones greater than today's date 'type' => 'DATE' // Let WordPress know we're working with date ) ), 'tax_query' => array( // Return only concerts (event-types) and events where "songs-of-ascent" is performing array( 'taxonomy' => 'event-types', 'field' => 'slug', 'terms' => 'concert', ), array( 'taxonomy' => 'speakers', 'field' => 'slug', 'terms' => 'songs-of-ascent', ) ) ) ); ?>
-
perchénon `'type'=> 'DATE'`?why not `'type' => 'DATE'` ?
- 5
- 2015-02-23
- Francisco Corrales Morales
-
Posso confermarei dubbi di @FranciscoCorralesMorales: devi specificareiltipo 'DATE',soprattuttoperchéi metacampi della datanon vengono salvati comenumeroma sottoforma di "Y-m-d" (attenzione aitrattini).Homodificato la risposta di Jonathan.I can confirm the doubts of @FranciscoCorralesMorales: you have to specify 'DATE' type, especially because date meta fields aren't saved as number but in the form of "Y-m-d" (please note hyphens). I've edited Jonathan's answer.
- 0
- 2017-02-17
- Marco Panichi
-
Per l'internazionalizzazione,potresti voler usare lafunzione di WordPress `date_i18n ()`,invece delnativophp `date ()`.For internationalization, you might want to use the WordPress function `date_i18n()`, instead of the php native `date()`.
- 0
- 2017-09-01
- Jake
-
- 2011-03-04
Inprimo luogo dipendein granparte da come la data vienememorizzatanelmeta valore. Ingenerale,è unabuonaideamemorizzare le datein MySQL come date/timestamp MySQL.
Itimestamp MySQL hannoilformato
Y-m-d h:i:s
.Tuttavia,è sempre unabuonaidea utilizzare lefunzioni dimodifica della data di WP. Pertanto,per ottenere la data correntein formato MySQL,utilizza
current_time('mysql')
.Performattare una data MySQLper la visualizzazione,usa
mysql2date($format, $mysql_date)
. In questo caso èmeglio visualizzare la data come configuratanelleimpostazioni,quindi usa$format = get_option('date_format');
.Permemorizzare una data selezionata dall'utente,dovraitranscodificarlain una data MySQL. Perfare ciò,ilmodopiù semplice,manonpiù sicuro,è
date('Y-m-d h:i:s', $unix_timestamp);
.$unix_timestamp
può spessoessere derivatotramitestrtotime($user_input)
.Tuttavia,
strtotime()
nonesegue autonomamentei controlli diintegrità,quindi èmeglio scrivere latuafunzione di conversazione.Per quanto riguarda l'intervallo dimesi,ecco unafunzione che sto utilizzandoper ottenerei limiti delmeseper qualsiasitimestamp MySQL:
function get_monthrange($time) { $ym = date("Y-m", strtotime($time)); $start = $ym."-01"; $ym = explode("-", $ym); if ($ym[1] == 12) { $ym[0]++; $ym[1] = 1; } else { $ym[1]++; } $d = mktime( 0, 0, 0, $ym[1], 1, $ym[0] ); $d -= 86400; $end = date("Y-m-d", $d); return array( $start, $end ); }
Se vuoi ottenerei limiti della settimana,WP ègià dotato di unafunzioneper questo:
get_weekstartend($time);
,chefornisce anchei limiti come un array.Puoi quindi utilizzarlineltuo argomento
meta_query
eseguendo due confronti separati.It largely depends on how your date is stored in the meta value in the first place. In general, it is a good idea to store dates in MySQL as MySQL dates/timestamps.
MySQL timestamps have the format
Y-m-d h:i:s
.However, it is always a good idea to use WP's own date mangling functions. As such, to get the current date in MySQL format, use
current_time('mysql')
.To format a MySQL date for display, use
mysql2date($format, $mysql_date)
. In this case it is best to display the date as configured in the settings, so use$format = get_option('date_format');
.To store a user-selected date, you'll have to transcode it into a MySQL date. To do so, the easiest - but not safest - way is
date('Y-m-d h:i:s', $unix_timestamp);
.$unix_timestamp
can often be derived viastrtotime($user_input)
.However,
strtotime()
doesn't do sanity checks on it's own, so it's best to write your own converstion function.As for getting the month range, here's a function i'm using to get the month boundaries for any MySQL timestamp:
function get_monthrange($time) { $ym = date("Y-m", strtotime($time)); $start = $ym."-01"; $ym = explode("-", $ym); if ($ym[1] == 12) { $ym[0]++; $ym[1] = 1; } else { $ym[1]++; } $d = mktime( 0, 0, 0, $ym[1], 1, $ym[0] ); $d -= 86400; $end = date("Y-m-d", $d); return array( $start, $end ); }
If you want to get the week boundaries, WP already comes with a function for that:
get_weekstartend($time);
, which also delivers the boundaries as an array.You can then use these in your
meta_query
argument by doing two separate comparisons.-
Non vuoi dire "Itimestamp MySQL hannoilformato" Y-m-d G:i: s "?"G:i: s" è di 24 ore,"h:i: s" di 12 ore.Don't you mean "MySQL timestamps have the format `Y-m-d G:i:s`"? `G:i:s` is 24-hour, `h:i:s` is 12-hour.
- 0
- 2018-08-11
- admcfajn
-
- 2013-07-30
Ciao di seguito,invio lamia soluzione.Dove homemorizzato la datanelformato
Y-m-d H:i
(come 2013-07-31 16:45).- Ordinatiin base alla data diinizio dell'evento.
-
Evento chetermina dopo oggi verràinterrogato solo da
meta_query
.date_default_timezone_set('Asia/Calcutta');
Hoimpostatoilfuso orariopredefinitoper lafunzione
date()
.$args = array( 'posts_per_page' => 3, 'orderby' => 'meta_value', 'meta_key' => 'event_start_date_time', 'order' => 'ASC', 'post_type' => 'events', 'meta_query' => array( array( 'key' => 'event_end_date_time', 'value' => date("Y-m-d H:i"), 'compare' => '>=', 'type' => 'DATE' ) ) ); query_posts( $args ); if( have_posts() ) : while ( have_posts() ) : the_post();
Hi below I am posting my solution. Where I have stored date in
Y-m-d H:i
format (like 2013-07-31 16:45).- Sorted according to Event start date.
Event which ending after Today will be queried only by
meta_query
.date_default_timezone_set('Asia/Calcutta');
I set default time zone for
date()
function.$args = array( 'posts_per_page' => 3, 'orderby' => 'meta_value', 'meta_key' => 'event_start_date_time', 'order' => 'ASC', 'post_type' => 'events', 'meta_query' => array( array( 'key' => 'event_end_date_time', 'value' => date("Y-m-d H:i"), 'compare' => '>=', 'type' => 'DATE' ) ) ); query_posts( $args ); if( have_posts() ) : while ( have_posts() ) : the_post();
Ho una chiamata query_postsin unmodello WP. Tramite l'utilizzo del Plugin More Fieldsposso dare all'amministratore del sito lapossibilità di creare unevento (customposttype)e quindiinserire una dataformattata: AAAA/mm/gg.
La domandaprincipale è; quale valore devopassare all'opzione valuenell'arraymeta_query? Attualmente sto cercando dipassare "date (" Y/m/d h:i A ")" (meno le virgolette),perché,a quanto ho capito,stamperà la data corrente oggi. Nonmi interessa l'ora della data,quindipotrebbeessereirrilevante. In ultima analisi,sto cercando di utilizzare l'opzione di confrontoperindividuarei prossimieventi,eventipassatiin luoghi diversi su questo sito. In un altropunto hoeffettivamentebisogno dipassare l'opzione value un array che stampailprimoe l'ultimogiorno delmese corrente,limitando l'output aglieventi che si verificano questomese.