admin管理员组

文章数量:1122832

I have looked to see if there is a simple function that only returns the name of a category on a post. I am looking to output it as a subheading for a list of posts but do not want it as a link and the the_category(); function only returns a link.

I also don't want it as a list. Any thoughts on how I can just get the "slug" of the category?

I have looked to see if there is a simple function that only returns the name of a category on a post. I am looking to output it as a subheading for a list of posts but do not want it as a link and the the_category(); function only returns a link.

I also don't want it as a list. Any thoughts on how I can just get the "slug" of the category?

Share Improve this question edited Aug 20, 2017 at 0:36 Johansson 15.4k11 gold badges43 silver badges79 bronze badges asked Aug 20, 2017 at 0:31 Chris ThomasChris Thomas 234 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

What you are looking for is get_the_category(). Retrieve a list of the categories, and then run a loop and only output their names:

$categories = get_the_category();
if ( ! empty( $categories ) ) {
    foreach( $categories as $category ){
        echo esc_html( $category->name );   
    }
}

This function returns an array of WP_Term objects. You can check the provided link for a list of available methods.

You can use get_the_terms with any taxonomy and output without the link like this :

$terms = get_the_terms( get_the_ID(), 'category' );
                     
if ( $terms && ! is_wp_error( $terms ) ) : 
    
$cats = array();
    
foreach ( $terms as $term ) {
    $cats[] = $term->name;
}
                            
$cats = join( ', ', $cats );

echo $cats;

endif;

}

本文标签: child themeCalling Category name without the link