Here we go :
Let’s say I have one cutom post type called “Movies”, and one custom taxonomy called “Directors” associated to this custom post type.
When I browse https://www.mydomain.com/movies/, I do have an archive page with all my custom posts filed under “Movies”. However, when I browse https://www.mydomain.com/directors/, I get a 404 page since taxonomies don’t have an automatic archive page url.
That’s why I create the “Directors” page on which I use a custom template called “taxonomy-tagcloud.php” (whatever the name).
My goals are :
- Display the Taxonomy name as h1 ;
- Display a short description (= the Page content) ;
- Then, display the list of terms under the “Directors” taxonomy :
- if the term has an image attached : display it ;
- if the term doesn’t have an image attached, display a default image.
That’s all, basically.
Here is the complete taxonomy-tagcloud.php :
<?php
/**
* @package WordPress
* @subpackage Toolbox
*/
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php // here, the page title and content ?>
<?php the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php //here, the code to display all terms with their own image, otherwise with the default image ?>
<?php
// I use $post->post_name to dynamically get the page's slug, i.e "directors"
$terms = apply_filters( 'taxonomy-images-get-terms', '', array(
'taxonomy' => $post->post_name,
) );
if ( ! empty( $terms ) ) {
print "\n" . '<ul>';
foreach( (array) $terms as $term ) {
print "\n" . '<li>';
if ( ! empty ( $term->image_id ) ) {
print "\n\t" . '<a href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . wp_get_attachment_image( $term->image_id, 'detail' );
print "\n\t" . '<span class="category-name">' . esc_html( $term->name ) . '</span>';
}
else {
print "\n\t" . '<a href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '"><img src="https://dummyimage.com/150/000/fff.png">';
print "\n\t" . '<span class="category-name">' . esc_html( $term->name ) . '</span>';
}
print "\n" . '</li>';
}
print "\n" . '</ul>';
}
?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Now, I made some other tests, and here is the problem I get with this code :
- if the taxonomy contains only one term, and if this only term doesn’t have any image attached, then the code works : I get the default image and the term link ;
- if the taxonomy contains many terms, and if at least one of these terms does have an image attached, then the terms without any image attached don’t show.
Do you have any idea about what the problem could be ?
PS : of course, I’m open to any other solution. Maybe using a page to achieve this isn’t the right way ? I’m close to get it working, though.