Home > Back-end >  Wordpress: showing post categories inside loop
Wordpress: showing post categories inside loop

Time:07-25

I have a small problem with showing all post categories for each post inside my loop on custom archive page.

This is How I try to show them:

$categories = get_the_terms( $post->ID, 'section' );
foreach ((array) $categories as $category) {    
echo  '<span >'. $category->name . '</span>';
}

As you can see there is a custom taxanomy "section" and I have there also custom post type called "games".

The problem is output. Some posts display correct cattegory names, some of them display none, and others show the same category name for example 7 times!

I was trying to debug WP and I got something like that for results where 0 categories shows:

Warning: Attempt to read property "name" on bool in /home/....

And for others

Trying to access array offset on value of type null in /home/....../archive-games.php on line 238

The same code works perfect on single post whre categories are shown correctly.

Any ideas how to fix that?

CodePudding user response:

I think this solution Is what you looking for. Copid from answer

$categories = get_the_category();
$separator = ' ';
$output = '';
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
    $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
}

Edit: - Improved

$categories = get_the_category();
if(!empty($categories)){
echo '<ul class='cats'>';
foreach( $categories as $category ) {
    echo '<li><a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>';
}
echo '</ul';
}

CodePudding user response:

It seems you are missing ID of the post or you are not mentioning correct taxonomy. Try adding :

get_the_ID();


$categories = get_the_terms( get_the_ID(), 'section' );
  • Related