1 min read
Create A WP Template for CPT to list Taxonomies with Link, Title & display Image from Posts
<?php
/*
Template Name: All Breeds
*/
get_header();
?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<section class="custom-taxonomy-categories">
<?php
$taxonomy = 'breeds'; // Replace 'your_custom_taxonomy' with the name of your custom taxonomy
$terms = get_terms($taxonomy);
if (!empty($terms) && !is_wp_error($terms)) {
foreach ($terms as $term) {
$term_link = get_term_link($term);
// Get posts associated with the current term
$args = array(
'post_type' => 'puppies', // Replace 'your_custom_post_type' with the name of your custom post type
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term->term_id,
),
),
'posts_per_page' => 1,
);
$posts = get_posts($args);
if (!empty($posts)) {
$post = $posts[0];
setup_postdata($post);
?>
<article class="custom-taxonomy-category">
<?php if (has_post_thumbnail()) : ?>
<div class="taxonomy-category-image">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('medium'); ?>
</a>
</div>
<?php endif; ?>
<div class="taxonomy-category-details">
<h2 class="taxonomy-category-title"><a href="<?php echo esc_url($term_link); ?>"><?php echo esc_html($term->name); ?></a></h2>
</div>
</article>
<?php
wp_reset_postdata();
}
}
} else {
echo '<p>No categories found.</p>';
}
?>
</section>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_footer(); ?>
<?php get_footer(); ?>
