Taxonomy List Page

Have you ever wanted to have the archive page for a custom taxonomy be a listing of the taxonomies? Easy! Just create a Page and have the slug match the base slug for the custom taxonomy! Then on that page, you could just create the index by hand, or use THIS shortcode!

In short, if you just call it as [taxonomy-list taxonomy="my-taxonomy"] it will pull in a list of all of the taxonomies available! You can tweak some other options, but that’s the gist.

The bulk of the code, however, is to let you pull in an image for each taxonomy item!

It does this by grabbing the first post (or other post type — you can specify this via the post_type argument) in that taxonomy that has a featured image, and using that as the featured image for the category! Easy peasy!

Just use that method via [taxonomy-list taxonomy="my-taxonomy" images="yup"] — or anything else that doesn’t evaluate to empty.

Also threw in some caching for good measure. It shoves the result in a transient for an hour.

There’s probably some other bits in here worth fleshing out — proper usage for title_li and depth, when images is turned on, etc etc, but for now, it serves my needs, and hopefully some of yours as well!


add_shortcode( 'taxonomy-list', 'my_taxonomy_list' );
function my_taxonomy_list( $atts ) {
	$args = shortcode_atts( array(
		'taxonomy' => 'category',
		'post_type' => 'post',
		'title_li' => '',
		'depth' => 1,
		'hide_empty' => 1,
		'images' => 0,
	), $atts );
	
	$get_posts_args = array(
		'post_type' => $args['post_type'],
		'number posts' => 1,
		'meta_query' => array(
			array(
				'key' => '_thumbnail_id',
				'compare' => 'EXISTS',
			),
		),
	);
	
	$key = 'my_taxonomy_list-' . md5( serialize( $args ) );
	if ( false === ( $result = get_transient( $key ) ) ) {
		ob_start();
		?>
		<ul class="taxonomy-list taxonomy-<?php echo $args['taxonomy']; ?>-list" data-taxonomy="<?php echo $args['taxonomy']; ?>">
			<?php
			if ( empty( $args['images'] ) ) {
				wp_list_categories( $args );
			} else {
				$cats = get_categories( $args );
				if( empty( $cats ) ) break;
				foreach( $cats as $cat ) {
					$img = '';
					$get_posts_args[$args['taxonomy']] = $cat->slug;
					if ( $posts = get_posts( $get_posts_args ) ) {
						$img = get_the_post_thumbnail( $posts[0]->ID );
					}
					?>
					<li><a href="<?php echo get_term_link( $cat ); ?>">
						<?php echo $img; ?>
						<?php echo $cat->name; ?>
					</a></li>
					<?php
				}
			}
			?>
		</ul>
		<?php
		$result = ob_get_clean();
		set_transient( $key, $result, HOUR_IN_SECONDS );
	}
	return $result;
}

Author: George Stephanis

Cooking, Code, Carpentry, Letterpress.