Come interrogare un tipo di post personalizzato con una tassonomia personalizzata?
Ho bisogno di recuperare qualsiasi post che utilizzi una tassonomia personalizzata.
$args = array(
'post_type' => 'adverts',
'advert_tag' => 'politics' // Non sembra funzionare.
);
query_posts($args);
while ( have_posts() ) : the_post();
//Mostra i Post
endwhile;
Dichiarazione della Tassonomia:
add_action( 'init', 'add_custom_taxonomy', 0 );
function add_custom_taxonomy() {
register_taxonomy('advert_tag', 'Adverts',
array(
'hierarchical' => true,
'labels' => array(
'name' => _x( 'Tag Annunci', 'nome generale tassonomia' ),
'singular_name' => _x( 'Tag Annuncio', 'nome singolare tassonomia' ),
'search_items' => __( 'Cerca Tag Annunci' ),
'all_items' => __( 'Tutti i Tag Annunci' ),
'parent_item' => __( 'Tag Annuncio Genitore' ),
'parent_item_colon' => __( 'Tag Annuncio Genitore:' ),
'edit_item' => __( 'Modifica Tag Annuncio' ),
'update_item' => __( 'Aggiorna Tag Annuncio' ),
'add_new_item' => __( 'Aggiungi Nuovo Tag Annuncio' ),
'new_item_name' => __( 'Nome Nuovo Tag Annuncio' ),
'menu_name' => __( 'Tag Annunci' ),
),
'rewrite' => array(
'slug' => 'tag-annunci',
'with_front' => false,
'hierarchical' => true
),
);
}
Dichiarazione del Tipo di Post Personalizzato:
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'Adverts',
array(
'labels' => array(
'name' => __( 'Annunci' ),
'singular_name' => __( 'Annuncio' ),
'add_new' => __( 'Aggiungi Nuovo' ),
'add_new_item' => __( 'Aggiungi un Nuovo Annuncio' ),
'edit' => __( 'Modifica' ),
'edit_item' => __( 'Modifica Annuncio' ),
'new_item' => __( 'Nuovo Annuncio' ),
'view' => __( 'Visualizza' ),
'view_item' => __( 'Visualizza Annuncio' ),
'search_items' => __( 'Cerca Annunci' ),
'not_found' => __( 'Nessun Annuncio trovato' ),
'not_found_in_trash' => __( 'Nessun Annuncio trovato nel Cestino' ),
),
'supports' => array(
'title',
'thumbnail',
),
'has_archive' => true,
'menu_position' => 10,
'public' => true,
'rewrite' => array(
'slug' => 'annunci'
),
'taxonomies' => array('advert_tag')
)
);
}
Prima di tutto non usare mai query_posts()
, leggi di più qui: Quando dovresti usare WP_Query vs query_posts() vs get_posts()?.
Devi usare WP_Query
per recuperare i post di cui hai bisogno. Leggi la documentazione. Nel tuo caso la query potrebbe essere così:
$the_query = new WP_Query( array(
'post_type' => 'Adverts',
'tax_query' => array(
array (
'taxonomy' => 'advert_tag',
'field' => 'slug',
'terms' => 'politics',
)
),
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
// Mostra i Post ...
endwhile;
/* Ripristina i Dati originali del Post
* NB: Poiché stiamo usando new WP_Query non stiamo interferendo con
* l'originale $wp_query e non è necessario resettarlo.
*/
wp_reset_postdata();

Ho appena notato che sembra estrarre tutti i post con il custom post type 'Adverts'. Tuttavia questo sembra funzionare:
$the_query = new WP_Query( array( 'post_type' => 'Adverts', 'advert_tag' => 'politics' ));

@Stephen {tax} è stato deprecato dalla versione 3.1 in favore di {tax_query} e {tax_query} è stato introdotto. Questo funziona ancora ma non dovremmo usare le funzioni deprecate.
tax_query viene utilizzato con un array di query tassonomiche. Stavo lavorando su un Custom Post Type per le FAQ e ha funzionato per me più o meno allo stesso modo in cui funziona l'argomento slug della tassonomia {tax} in WP_Query.

Sto utilizzando questa query per recuperare i custom post (Post FAQ) con la relativa tassonomia personalizzata (faq_category). Dal momento che il parametro {taxonomy} negli argomenti di WP_Query è stato deprecato dalla versione 3.1 ed è stato introdotto {tax_query}, di seguito il codice che funziona perfettamente.
$query = new WP_Query( array(
'post_type' => 'faqs', // nome del tipo di post
'tax_query' => array(
array(
'taxonomy' => 'faq_category', // nome della tassonomia
'field' => 'term_id', // term_id, slug o name
'terms' => 48, // id del termine, slug del termine o nome del termine
)
)
) );
while ( $query->have_posts() ) : $query->the_post();
// inserisci qui il codice da eseguire...
endwhile;
/**
* reimposta la query originale
* dovremmo usare questo per reimpostare wp_query
*/
wp_reset_query();

Questa è la risposta corretta - la risposta accettata non filtrerà per tassonomia poiché tax_query richiede un array di array. Questo metodo nidificato è essenziale per far funzionare questo. Grazie per la tua risposta )

Sì, anche questo mi ha aiutato a far funzionare il template delle tassonomie. Grazie!

Ciao @AamerShahzad ho esattamente la stessa domanda e ho usato la tua risposta ma la pagina non sta estraendo nessun post. Puoi aiutarmi? https://stackoverflow.com/questions/55783769/how-do-i-pull-only-one-category-from-custom-post-type-in-a-template

Ecco il codice che funziona come per magia. Sto recuperando tutti i post per il custom post_type "university_unit" con la tassonomia personalizzata "unit_type" e molteplici termini tassonomici come "directorate" e "office". Spero che possa essere d'aiuto.
<?php
// Argomenti per la query personalizzata
$args = array(
'post_type' => 'university_unit', // Tipo di post personalizzato
'posts_per_page' => -1, // Mostra tutti i post
'orderby' => 'title', // Ordina per titolo
'order' => 'ASC', // Ordine ascendente
'tax_query' => array(
array(
'taxonomy' => 'unit_type', // Nome della tassonomia
'field' => 'slug', // Campo da utilizzare per il confronto
'terms' => array('directorate', 'office') // Termini da cercare
)
)
);
$Query = new WP_Query($args);
if($Query -> have_posts()):
while($Query -> have_posts()):
$Query -> the_post();
?>
<div class="cm-post-list-item">
<article>
<div class="cm-post-head">
<h3 class="cm-text-blue">
<a href="<?php the_permalink(); ?>"><?php the_title();?></a>
</h3>
</div>
<div class="cm-post-body"><?php the_excerpt();?></div>
</article>
</div>
<?php
endwhile;
else:
"Nessun Ufficio Amministrativo Trovato. Riprova più tardi";
endif;
wp_reset_postdata();
?>

Questo mi ha aiutato a ottenere tutti i post elencati sotto ciascun termine per una tassonomia personalizzata per CPT
<?php
// Ottieni l'elenco di tutti i termini della tassonomia -- In semplici titoli di categorie
$args = array(
'taxonomy' => 'project_category',
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories($args);
// Per ogni termine della tassonomia personalizzata ottieni i relativi post tramite term_id
foreach($cats as $cat) {
?>
<a href="<?php echo get_category_link( $cat->term_id ) ?>">
<?php echo $cat->name; ?> <br>
<?php // echo $cat->term_id; ?> <br>
</a>
<?php
// Argomenti della Query
$args = array(
'post_type' => 'portfolio', // il tipo di post
'tax_query' => array(
array(
'taxonomy' => 'project_category', // il vocabolario personalizzato
'field' => 'term_id', // term_id, slug o name (Definisci per cosa vuoi cercare il termine sottostante)
'terms' => $cat->term_id, // fornisci gli slug dei termini
),
),
);
// La Query
$the_query = new WP_Query( $args );
// Il Loop
if ( $the_query->have_posts() ) {
echo '<h2>Elenco dei post taggati con questo tag</h2>';
echo '<ul>';
$html_list_items = '';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$html_list_items .= '<li>';
$html_list_items .= '<a href="' . get_permalink() . '">';
$html_list_items .= get_the_title();
$html_list_items .= '</a>';
$html_list_items .= '</li>';
}
echo $html_list_items;
echo '</ul>';
} else {
// nessun post trovato
}
wp_reset_postdata(); // reimposta il $post globale;
?>
<?php } ?>

Questa risposta non è più valida poiché WordPress ha modificato le informazioni sui parametri della tassonomia. Si prega di utilizzare questo metodo. Funzionerà. Ha funzionato per me. "tax_query" viene sostituito con "tax". Spero che funzioni.
$the_query = new WP_Query( array(
'post_type' => 'Adverts',
'tax' => array(
array (
'taxonomy' => 'advert_tag',
'field' => 'slug',
'terms' => 'politics',
)
),
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
// Mostra i Post ...
endwhile;
/* Ripristina i Dati originali del Post
* NB: Poiché stiamo utilizzando new WP_Query non stiamo interferendo con
* il $wp_query originale e non è necessario resettarlo.
*/
wp_reset_postdata();

È esattamente l'opposto - tax
era il vecchio metodo, tax_query
è il metodo attuale (dalla v3.1+).

WordPress è famoso per essere retrocompatibile. Il vecchio metodo funziona ancora, ma è stato deprecato, quindi potrebbe essere rimosso in futuro ed è più sicuro utilizzare il nuovo metodo.
