Display a post's category within the wordpress loop?

前端 未结 4 617
不知归路
不知归路 2021-02-11 07:19

Okay, so I have a Wordpress template that I created that only displays posts that have the \"workout\" category associated with it. Within the loop that displays those, I want t

相关标签:
4条回答
  • 2021-02-11 07:55

    Get the post category if you have a custom post_type

    <?php
    $categories = get_the_terms( $post->ID, 'taxonomy' );
    // now you can view your category in array:
    // using var_dump( $categories );
    // or you can take all with foreach:
    foreach( $categories as $category ) {
        echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
    } ?>
    

    click here for detail

    0 讨论(0)
  • 2021-02-11 07:57

    Get the category objects:

    $cats = get_the_category($id);
    

    Just echo the name:

    echo $cats[0]->name;
    

    If you want to output a link, use this:

    <a href="<?php echo get_category_link($cats[0]->cat_ID); ?>">
        <?php echo $cats[0]->name; ?>
    </a>
    

    Note: instead of wp_get_post_categories($id), you could just use get_the_category().


    Update: if you want to display all the categories, just loop through them:

    <?php foreach ( $cats as $cat ): ?>
    
        <a href="<?php echo get_category_link($cat->cat_ID); ?>">
            <?php echo $cat->name; ?>
        </a>
    
    <?php endforeach; ?>
    
    0 讨论(0)
  • 2021-02-11 08:06

    If anybody else needs help with this you can use this inside posts loop:

    <p><?php _e( 'Category: ', 'themename' ); the_category(', '); // Separated by commas ?></p>
    
    0 讨论(0)
  • 2021-02-11 08:09

    Thanks Joseph. I have extended your code so that the word 'Category' changes to 'Categories' when there are more than one category. There may be a better way of doing this but I couldn't find it anywhere :)

    <p>
        <?php 
        $id = get_the_ID();
        $cats = get_the_category($id);
        echo ( count($cats) == 1  ? 'Category: ' : 'Categories: ');
        $c = 0; $n = 0;
        $c = count($cats);
        foreach ( $cats as $cat ):
            $n++; ?>
            <a href="<?php echo get_category_link($cat->cat_ID); ?>">
                <?php echo $cat->name; echo ( $n > 0 && $n < $c ? ', ' : ''); ?>
            </a>
        <?php endforeach; ?>
    </p>
    
    0 讨论(0)
提交回复
热议问题