Sempre più spesso facciamo uso dei custom post type per poter realizzare siti web sempre più evoluti in wordpress.
Abbiamo già visto in passato cosa sia e come si possa creare un custom post type.
Vediamo adesso cosa dobbiamo fare per poter creare il nostro template in wordpress, estraendo i custom post type:
$lista = new WP_Query( array('post_type' => 'your-custom-post-type', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'your-taxonomy', 'field' => 'slug', 'terms' => $term ) ), 'orderby' => 'title', 'order' => 'DESC') );
La nuova versione di WP_Query consente di filtrare i dati di tipo “custom post type”, grazie al parametro tax_query. Ecco cosa si dice la documentazione a riguardo:
Show posts associated with certain taxonomy.
- {tax} (string) – use taxonomy slug. Deprecated as of Version 3.1 in favor of ‘tax_query‘.
- tax_query (array) – use taxonomy parameters (available with Version 3.1).
- taxonomy (string) – Taxonomy.
- field (string) – Select taxonomy term by (‘id’ or ‘slug’)
- terms (int/string/array) – Taxonomy term(s).
- include_children (boolean) – Whether or not to include children for hierarchical taxonomies. Defaults to true.
- operator (string) – Operator to test. Possible values are ‘IN’, ‘NOT IN’, ‘AND’.
Vediamo ora di rendere tutto più interessante.
Specifica: dobbiamo realizzare un cartellone di spettacoli per un sito web per teatri, ed il cliente ci chiede di raggruppare gli spettacoli in base al mese, ordinandoli da gennaio a dicembre all’interno dell’anno. Come possiamo estrarre questi dati?
Dobbiamo far ricorso alla query di base evidenziata in precedenza, filtrando per i meta_value delle date spettacolo:
$loop = new WP_Query(array('post_type' => 'spettacolo', 'posts_per_page' => -1, 'meta_query' => array( array( 'value' => array($dataDa, $dataA), 'type' => 'DATE', 'compare' => 'BETWEEN' ) ), 'meta_key' => 'data_da', 'orderby' => 'meta_value', 'order' => 'ASC') );
Possiamo notare un paio di elementi interessanti in questa query:
- abbiamo applicato il filtro SQL BETWEEN per estrarre i custom post type ‘spettacolo’ che abbiano una data spettacolo compresa tra “dataDa” e “dataA”;
- abbiamo imposto l’ordinamento per un meta_value “dataDa”, di modo da ordinare i risultati sulla base della prima data dello spettacolo