Visualizzare i post wp_query della stessa categoria del post
Nella mia pagina del post sto cercando di visualizzare un elenco di altri post della stessa categoria del post originale. Finora ho questo codice che non sembra funzionare:
<?php
$args = array(
'post_type' => 'article',
'posts_per_page' => 5,
'post__not_in' => array( get_the_ID() ),
'category' => array( get_the_category() ),
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query( $args );
?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<a class="popup-article-picture" href="<?php the_permalink(); ?>" style="background-image: url('<?php the_post_thumbnail_url(); ?>');"></a>
<a class="popup-article-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endwhile; endif; wp_reset_postdata(); ?>
Ho trovato una risposta:
<?php
$cats = get_the_category();
$args = array(
'post_type' => 'article',
'post__not_in' => array( get_the_ID() ),
'posts_per_page' => 5,
'cat' => $cats[0]->term_id,
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query( $args );
?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<!--HTML-->
<?php endwhile; endif; wp_reset_postdata(); ?>

stai cercando di interrogare il custom post type chiamato article
. stai utilizzando le categorie predefinite di WordPress per il post type article
? oppure hai registrato una tassonomia personalizzata per quel post type? presumo tu stia usando la categoria predefinita di WordPress per il CPT
.
il primo passo è ottenere la categoria corrente dalla pagina singola. la seguente funzione restituirà le categorie associate al post dall'esterno del loop.
get_the_category();
restituirà un array di oggetti term. e dovrai ottenere lo slug da questo array da passare alla query. supponiamo di avere solo una categoria assegnata per il singolo post.
$category_obj = get_the_category();
$category = $category_obj[0]->slug;
ora puoi usarlo nella tua query per i post correlati.
$args = array(
'post_type' => 'article',
'posts_per_page' => 5,
'category' => $category,
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query( $args );
e se stai utilizzando una tassonomia personalizzata per il post type faccelo sapere così possiamo aiutarti riguardo alle tassonomie personalizzate.
