Get a list of commas separated categories inside a loop

admin2025-06-05  9

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?

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?

Share Improve this question asked Nov 5, 2011 at 9:19 Omar AbidOmar Abid 4163 gold badges6 silver badges19 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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 ;)

Without a loop

get_the_category_list(',');

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 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749077339a316164.html

最新回复(0)