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
After: using the second snippet
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.
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!
The topic ‘Separate Custom Taxonomy By Comma’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.