This guide is going to dive into some PHP templating in WordPress.

I just got finished making a complex website that needed to display a long list of custom post types in a table (and do a bunch of other stuff).

The end result turned out really nice, but I had the hardest time finding a simple explanation, of how you can show a list of custom post types with its custom taxonomy.

I figured I would save myself a lot of time in the future if I documented what I did (and probably save somebody else some time, as well).

Diagram of the website pointing out the custom taxonomies, and custom posts inserted into a master table.
Website displaying over 600 domain names in a table.

Display Custom Posts and Taxonomies on a Page

I created a custom post type for domains, along with a custom taxonomy.

Then I made a unique PHP template named ‘Domain List’ template-domainlist.php to write my custom query code.

The following is a simplified version of my display table…

<?php // Query Domain Post Types
$posts = get_posts(array( 'posts_per_page' => -1,'post_type' => 'domain', ));
if( $posts ): ?>

<table>
	<?php foreach( $posts as $post ): setup_postdata( $post ); 
	$domain = get_the_title();
	$terms = get_the_terms( $post->ID, 'domain_cat' ); foreach ( $terms as $term ); ?>
	<tr>
		<td><?php echo $domain; ?></td>
		<td><a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
 			<?php echo esc_html( $term->name ); ?> 
		</a>
		</td>
	</tr>
<?php endforeach; ?>
</table>

<?php wp_reset_postdata(); ?>
<?php endif; ?>

To use this code, replace ‘domain’ ( where it says post_type’ => ‘domain’) with your own custom post type. Then replace ‘domain_cat‘ with your own custom taxonomy name.

The result will look something like this…

screenshot of the resulting code, showing each domain name with a category link.
The above code displays each post with it’s custom taxonomy link.

Of course, you don’t need to put it in a table. Replace <table> with <section>, <tr> with <div>, and <td> with <p> and you’ll have the framework for something entirely different.

So, what do you think? Was this code helpful? Let us your your thoughts in the comments below…

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *