1

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
 <?php  foreach((get_the_category()) as $category) { ?>
  <a href="<?php echo $category->category_nicename . ' '; ?>"><?php echo $category->category_nicename . ' '; ?></a>

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

  • what is "category_nicename" in above code please point out it using question code. Thanks – Super Model Sep 6 '18 at 10:58
  • @SuperModel its a category slug. – DHL17 Sep 6 '18 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.