Reputation: 435
I am trying to display a custom post type that has a custom taxonomy, but I am not having any luck. Nothing is showing up. I appreciate any help.
Post type = university
Custom Taxonomy slug = country
I wanted to show all the country list using WP_Query as there are some custom fields in this taxonomy. Also, on click of any country, it should redirect to a country page with its details
Below is my code
<?php
$args = array(
'post_type' => 'university',
'tax_query' => array(
array(
'taxonomy' => 'country'
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
<a title="<?php the_title(); ?>">
<h3><?php the_title(); ?></h3>
</a>
<?php
}
}
wp_reset_postdata();
?>
Upvotes: 1
Views: 18870
Reputation: 9373
I have modified your code, Please try it.
<?php
$custom_terms = get_terms('country');
$args = array(
'post_type' => 'university',
'tax_query' => array(
array(
'taxonomy' => 'country',
'field' => 'slug',
'terms' => $custom_terms[0]->slug, // or the category name e.g. Germany
),
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
<a title="<?php the_title(); ?>">
<h3><?php the_title(); ?></h3>
</a>
<?php
}
}
wp_reset_postdata();
?>
We get all the terms of a taxonomy, loop through them, and fire off a title link to each post that belongs to that term.
Upvotes: 7