Come utilizzare meta_query con valori multipli in WordPress
Ho bisogno del tuo aiuto.
Ecco il mio problema: ho un custom post type "Player". Questo CPT ha un campo personalizzato "Seasons". Le stagioni possono avere valori multipli separati da virgola - per esempio "2014,2015,2016" ecc.
Ora ho bisogno di filtrare la lista dei giocatori che hanno giocato in determinate stagioni - per esempio 2015 e 2016.
E ora ho bisogno del tuo aiuto con questa wp_query
. Ho provato questo codice, ma non funziona :-/
query_posts(
array(
'post_type' => 'player',
'meta_query' => array(
array(
'key' => 'seasons',
'value' => array( '2015','2016'),
'compare' => 'IN',
),
),
)
);
Per favore aiutami.
Grazie,
libor

Ampliando un po' la risposta di @dgarceran
Generalmente, usare la classe WP_Query
è probabilmente una buona idea per interrogare i post.
Dovremo passare degli argomenti a quella query.
Nel tuo caso probabilmente vorremo usare uno dei seguenti:
- "Parametri dei Custom Field" -
meta_query
- "Parametri delle Tassonomie" -
tax_query
Per un esempio quasi completo di tutte le opzioni mi piace fare riferimento a questo gist: https://gist.github.com/luetkemj/2023628.
Vedi anche il Codex: https://codex.wordpress.org/Class_Reference/WP_Query
Entrambi prendono un array di array associativi, es:
Nota: Userò una sintassi compatibile con PHP 5.4 in poi
$meta_query_args = [
[
'key' => 'season',
'value' => [ '2015', '2016' ],
'compare' => 'IN',
],
];
Possiamo inserire questi argomenti nella nostra istanza di WP_Query
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Imposta questo a un limite ragionevole
'meta_query' => $meta_query_args,
];
$the_query = new WP_Query( $args );
Quello che succede a questo punto è che WordPress controllerà tutti i post che corrispondono al tuo custom post type player
. Poi, interrogherà i metadati che hai impostato con la chiave season
. Qualsiasi post corrispondente a 2015
o 2016
verrà restituito.
Nota: usare meta_query
in questo modo generalmente non è raccomandato perché è un po' pesante per il database. Il consenso sembra essere che interrogare le tassonomie sia più performante (ma non citatemi su questo, non ho trovato la fonte)
Quindi per un'alternativa veloce, consiglio il seguente esempio:
$tax_query_args = [
[
'taxonomy' => 'season',
'field' => 'slug',
'terms' => [ '2015', '2016' ],
'operator' => 'IN',
],
];
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Imposta questo a un limite ragionevole
'tax_query' => $tax_query_args,
];
$the_query = new WP_Query( $args );
Ora possiamo effettivamente ciclare attraverso i dati, ecco un esempio di markup:
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, 'season', true ); // esempio se vuoi ancora usare i post meta
$season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( 'Stagione: ' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
Quando usi WP_Query
specialmente nei template, assicurati di terminare con wp_reset_postdata();
Mettendo tutto insieme (tl;dr)
$tax_query_args = [
[
'taxonomy' => 'season',
'field' => 'slug',
'terms' => [ '2015', '2016' ],
'operator' => 'IN',
],
];
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Imposta questo a un limite ragionevole
'tax_query' => $tax_query_args,
];
$the_query = new WP_Query( $args );
?>
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, 'season', true ); // esempio se vuoi ancora usare i post meta
$season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( 'Stagione: ' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
<?php
wp_reset_postdata();
Vista front-end della nostra query:
Vista dashboard dei post del CPT Player:
Spero che questo fornisca un po' di contesto

Ecco come lo farei utilizzando The Loop e seguendo gli esempi del Codex.
$args = array(
'post_type' => 'player',
'meta_key' => 'age',
'meta_query' => array(
array(
'key' => 'seasons',
'value' => array( 2015, 2016 ), // oppure array( '2015', '2016' )
'compare' => 'IN',
),
),
);
// La Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// fai qualcosa
}
} else {
// nessun post trovato
}
// Ripristina i dati originali del Post
wp_reset_postdata();
Il tuo problema è che stai aggiungendo i valori in un'unica stringa come "2015,2016,2017"... e dovresti invece separare ogni valore in un campo diverso. Con ACF hai la possibilità di aggiungere un ripetitore per le stagioni, e puoi anche creare una tassonomia personalizzata per salvare questi valori, invece che usare un post meta. Se non vuoi cambiare questo approccio, dovresti prima recuperare i tuoi dati post meta con get_post_meta, e usare la funzione explode di PHP.
