2

I want to get the list of categories of a post inside the loop. Normally, I would use

the_category(', ');

But this does output a link, and I only want the category name. Any ideas?

3 Answers 3

3

Should be easy enough i think..

<?php 
foreach((get_the_category()) as $category) { 
    //this would print cat names.. You can arrange in list or whatever you want..
    echo '<span>'.$category->cat_name .'</span>';
} 
?>

.
Hope This Helps ;)

4

Without a loop

get_the_category_list(',');
2
  • 2
    He asks for a list without links, this outputs links as well.
    – Florian
    Commented Apr 16, 2015 at 8:58
  • 1
    You could run it through strip_tags() to solve the issue of links: echo strip_tags( get_the_category_list( ', ' ) );
    – Howdy_McGee
    Commented Oct 11, 2019 at 21:19
1

Below code might help outside the loop. I am using it on save_post action hook.

// get the assigned terms to the post
$terms = get_the_terms( $post_id, 'category' );
// create an empty array for storing category names
$terms_meta = [];
if ( ! empty( $terms ) ) {
    foreach ( $terms as $term ) {
        $terms_meta[] = $term->name;
    }
}

if ( ! empty( $terms_meta ) ) {
    $terms_string = implode( ', ', $terms_meta );
} else {
    $terms_string = '';
}

print_r( $terms_string );
1
  • 1
    Very good, it works fine for me! Commented Jul 12, 2019 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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