0

I have in my code the following variable to call the title of the categories.

<?php 
      $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');

      foreach ($categories as $category) {
            $cats .= $category->name . ', ';
            echo rtrim($cats, ', ');
          }
?>

The problem is that in the last post of the loop I duplicated the categories and printed them all. enter image description here

in fact it is printed by post from less to more. If I use the following code fragment, I print it well but without commas

foreach ($categories as $category) {
    echo '<span>'.$category->name .'</span>';
}

If someone would be so kind to guide me I would be very grateful, this brings me

1

In this line:

$cats .= $category->name . ', ';

You append a name of category to variable called $cats.

But you never reset this variable. So every post appends its categories to the same variable.

So here’s how to fix this:

<?php
  $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');
  $cats = ''; // set empty string as  value

  foreach ($categories as $category) {
        $cats .= $category->name . ', ';
        echo rtrim($cats, ', ');
  }
?>

Of course you can also add commas to your second code:

foreach ($categories as $i => $category) {
         if ( $i ) echo ', ';
         echo '<span>'.$category->name .'</span>';
}
0

You can add comma this way

<?php 
$post_cat = get_the_terms( $custom_args->ID, 'veranstaltungen-category' );

$result_pro_cat = "";

foreach ( $post_cat as $post_cat_key => $post_cat_value ) {
    $result_pro_cat .= '<a href="' . esc_url( get_category_link( $post_cat_value->term_id ) ) . '">' . $post_cat_value->name . '</a>' . ', ';  
} 
echo rtrim( $result_pro_cat, ', ' );
0

You have to just define $cats null variable, so every time it reset the cat value null. and echo $cats out side of foreach loop. that's it.

      $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');
      #define blank 
      $cats = "";
      foreach ($categories as $category) {
            $cats .= $category->name . ', ';
       }
       # echo out of foreach loop
       echo rtrim($cats, ', ');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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