I have custom post type name "resources" and taxonomy called "type" with lot of terms in it. I do not want to create custom template for each term like taxonomy-type-{term}.php every time I add new term.
What I am trying to achieve here is a single page where it handle to check each terms. If the current term is "24622", show content and so on, but I want it dynamic so I don't want to input term ID each time a new term created.
The code that I use that works so far for single term is this:
<?php
$args = array (
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => 24622 //I WANT IT DYNAMIC
)
)
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
}
?>
Please help. Thanks!
UPDATE
Here is the code that works for now but it fetches posts wrong order.
// get all terms used by current post for specific category
$terms = get_the_terms(get_the_ID() , 'type');
// if $terms is array convert array of term objects to array of term IDs
if(is_array($terms)){
$term_ids = wp_list_pluck($terms, 'term_id');
foreach($terms as $term) {
$post_ids[] = $term->term_id;
}
// proceed with tax query
$args = array(
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => $term->term_id
)
)
);
$loop = new WP_Query($args);
if ($loop->have_posts()) {
$term = $wp_query->queried_object;
while ($loop->have_posts()):
$loop->the_post();
// Output what you want
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
}
wp_reset_postdata();
}
If I click the "Case studies (2)" it supposed to show 2 posts but show 1 post. In "Advocacy maps (1)", it shows 2 posts.
Post 1 is related to "Case studies" and "Advocacy maps" terms
Post 2 is related to "Case studies" and "Land monitoring reports"