Display Custom Category (taxonomy) Name in Custom Post Type

I have a custom post type called results. I also have categories for that specific post type.

My goal is to echo out the category name of the post in the custom post type as set it as an HTML class.

Here is the code that sets up my custom post type and custom taxonomy:

// Create custom post type
function create_posttype() {
    register_post_type( 'Results',
        array(
            'labels' => array(
                'name' => __( 'Results' ),
                'singular_name' => __( 'Results' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'results'),
            'taxonomies'  => array( 'results', 'result-category' ),
        )
    );
}
add_action( 'init', 'create_posttype' );

//Create category for specific post type
function tr_create_my_taxonomy() {
    register_taxonomy(
        'results-categories',
        'results',
        array(
            'label' => __( 'Result Categories' ),
            'rewrite' => array( 'slug' => 'result-category' ),
            'hierarchical' => true,
        )
    );
}
add_action( 'init', 'tr_create_my_taxonomy' );

Heres how im displaying the custom post type on one of my pages:

<?php
$query = new WP_Query( array( 'post_type' => 'Results',  'posts_per_page' => -1 ) );
if ( $query->have_posts() ) : ?>
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
        <div class="result-item">
            <div class="<?php //GOAL: code to display the category ?>"></div>
        </div>
    <?php endwhile; wp_reset_postdata(); ?>
<?php else : ?>
<?php endif; ?>

Thanks!

1 Answer
1

<?php  foreach((get_the_category()) as $category) { ?>
      <a href="https://wordpress.stackexchange.com/questions/275711/<?php echo $category->category_nicename ." '; ?>"><?php echo $category->category_nicename . ' '; ?></a>
<?php } ?>

insert above code here //GOAL: code to display the category//

Leave a Comment