Support

Account

Home Forums ACF PRO Separate Custom Taxonomy By Comma

Solved

Separate Custom Taxonomy By Comma

  • Hi,

    How can I display my custom taxonomies separated by comma “,” in the frontend?
    I’m using the below code:

    <?php 
    $terms = get_field('location_type');
    if( $terms ): ?>
    <?php foreach( $terms as $term ): ?>
    <a href="<?php echo get_term_link( $term ); ?>">  <?php echo $term->name; ?> </a>
    <?php endforeach; ?>
    <?php endif; 
    ?>
  • There are several ways to do this, one involves using a counter so that you don’t add a comma after the last one.

    
    <?php 
      $terms = get_field('location_type');
      if( $terms ):
        $total = count($terms)
        $count = 1;
        foreach( $terms as $term ):
          ?>
            <a href="<?php 
              echo get_term_link( $term ); ?>"><?php 
              echo $term->name; ?></a>
          <?php 
          if ($count < $total) {
            echo ', ';
          }
          $count++;
        endforeach;
      endif; 
    ?>
    
  • Thanks, John. I like this idea you provided.
    But unfortunately, this code snippet didn’t work.
    Is there any other way?

  • What do you mean “it doesn’t work”? are you getting an error? What is it doing?

  • as shown in the below pics, that’s what I get (before & after)

    Before: using the first code snippet
    Before

    After: using the second snippet
    After

  • https://codex.wordpress.org/Debugging_in_WordPress, sometimes little bugs, like missing semicolons, happen when people post code on a forum. How do you debug any code you create yourself?

    
    <?php 
      $terms = get_field('location_type');
      if( $terms ):
        $total = count($terms);
        $count = 1;
        foreach( $terms as $term ):
          ?>
            <a href="<?php 
              echo get_term_link( $term ); ?>"><?php 
              echo $term->name; ?></a>
          <?php 
          if ($count < $total) {
            echo ', ';
          }
          $count++;
        endforeach;
      endif; 
    ?>
    
  • Excellent! it works.
    Final Result

    I’m still a PHP beginner and thanks for the link of debugging.
    I’ll use those methods from now on 🙂

    thank you so much John.

  • Hi!
    I need this code, but it doesn’t work with the plugin CodeSnippet (my website goes in Fatal Error). Can you help me? How can I insert that code in CodeSnippet?
    I don’t want the bulleted list (screenshot attached), but commas.

    Thank you!

Viewing 8 posts - 1 through 8 (of 8 total)

The topic ‘Separate Custom Taxonomy By Comma’ is closed to new replies.