WordPress – Display Custom Post Types (CPTs), Custom Taxonomies and Terms

Place any of the following code with your functions.php and it display on any page of your site, before the wordpress header. I use the code for debugging and understanding what custom post types and taxonomies exist, but you can expand on the snippets to build functions that can work with the data however you want.

To display all custom post types that are “not public”.

<?php // get all post types 
$post_types=get_post_types(array('public'=>false),'names'); 
foreach ($post_types as $post_type ) {
  echo '

'. $post_type. '

'; } ?>

To display only the “public” Post Types change “public => false” to ‘true’ (this will also show the default post types such as posts and pages). To exclude default post types add ‘_builtin’ => false within the get_post_types array.

The following code will display the name of existing taxonomies to include the default taxonomies. If you need to know what taxonomies are associated with what post type you need to change ‘name’ to object and the taxonomy object will be dumped towards the bottom of each object you can see a post types attribute for the taxonomy which will give the post types associate as an array.

<?php //get all taxonomies ?>

<?php var_dump(get_taxonomies( $args, 'name', $operator )) ?> 

To display all of the terms within a taxonomy use the following code. Change taxonomy => ‘name’ to the taxonomy you wish to display the terms for.

<?php //get all term for custom taxonomy "genre" ?>
    <?php $args = array('taxonomy' => 'genre'); $tax_menu_items = get_categories( $args ); foreach ( $tax_menu_items as $tax_menu_item ): ?>
  • <?php echo $tax_menu_item->name; ?>
  • <?php endforeach; ?>

Leave a Reply

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