skip to Main Content

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 class="kat-label">'. $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?

3

Answers


  1. Chosen as BEST ANSWER

    OK. So there was a BUG in WPML (I have checked the WPML changelog) multilangual plugin. Updating WPML fixed the problem.


  2. 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';
    }
    
    Login or Signup to reply.
  3. 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' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search