tax_query in get_posts() non funziona?

11 apr 2013, 11:30:53
Visualizzazioni: 38.6K
Voti: 9

Sto cercando di stampare tutti i post all'interno di ogni tassonomia per un tipo di post personalizzato chiamato product (prodotti jigoshop). Quindi ottengo tutte le tassonomie usando $cats = get_terms('product_cat');, poi le scorro tutte e cerco di ottenere tutti i post che sono all'interno della tassonomia. Il problema è che non funziona. Restituisce solo un risultato vuoto!

$uposts = get_posts(array(
    'post_type' => 'product',
    'numberposts' => -1,
    'tax_query' => array(
        'taxonomy' => $cat->taxonomy,
        'field' => 'slug',
        'terms' => array($cat->slug),
        'operator' => 'IN'
    )
));

Se cambio 'terms' => array($cat->slug) in 'terms' => $cat->slug restituisce tutti i post, come se ignorasse completamente la tax_query.

Qualche idea su cosa sta causando questo fallimento? Ho provato a modificare operator, cambiando field in ID (e anche inviando $cat->ID come termine)... niente funziona!

$cat ha i seguenti valori:

stdClass Object
(
    [term_id] => 114
    [name] => Ny testkategori
    [slug] => ny-testkategori
    [term_group] => 0
    [term_taxonomy_id] => 115
    [taxonomy] => product_cat
    [description] => 
    [parent] => 0
    [count] => 2
    [meta_id] => 3
    [jigoshop_term_id] => 114
    [meta_key] => order
    [meta_value] => 1
)

Quindi $cat->slug e $cat->taxonomy sono valori validi.

0
Tutte le risposte alla domanda 1
3
25

Il tax_query richiede un array di array di argomenti per la query tassonomica (accetta un array di array) ma stai utilizzando solo un singolo array. Il codice corretto è il seguente.

$uposts = get_posts(
    array(
        'post_type' => 'product',
        'numberposts' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => $cat->taxonomy,
                'field' => 'slug',
                'terms' => array($cat->slug),
                'operator' => 'IN',
            )
         )
    )
);

Per maggiori informazioni visita questa pagina.

11 apr 2013 11:39:32
Commenti

Oh certo! Che stupido, ho passato più di un'ora a cercare di risolvere. Grazie mille!

qwerty qwerty
11 apr 2013 12:30:07

fortunato te, io ci ho passato tre giorni :( C'è qualcosa tipo un feedback su quanti post vengono recuperati o meglio PERCHÉ non vengono trovati? Un sacco di tutorial ed esempi, anche qui riguardano versioni più vecchie o comunque non hanno funzionato per me.

piotao piotao
8 nov 2018 15:48:56

L'URL della documentazione è cambiato. La documentazione per i parametri di tassonomia di WP_Query ora si trova qui: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

Tomas Eklund Tomas Eklund
23 mar 2020 18:00:12