0

I'm trying to show terms of custom taxonomies. I have that. But, my problem is how to separate when I have multiple terms.
My code:

<ul class="slides">
    <?php $loop = new WP_Query( array( 'post_type' => 'member', 'posts_per_page' => -1 ) ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); $do_not_duplicate = $post->ID; ?>
        <li>
            <h2><?php $terms = get_terms('department');
                foreach ( $terms as $term ) {
                    echo $term->name.' and ';
                }
            ?></h2>
            <?php the_post_thumbnail('full'); ?>
            <div class="caption">
                <h4><?php the_title(); ?></h4>
                <h5><?php $terms = get_terms('position');
                    foreach ( $terms as $term ) {
                        echo $term->name.' and ';
                    }
                ?></h5>
                <?php the_content(); ?>
                <a href="<?php the_permalink(); ?>">See Full Biography</a>
            </div>
        </li>
    <?php endwhile; wp_reset_query(); wp_reset_postdata(); ?>
</ul>

With this I am able to display all terms used (good). But, I need it to say "and" only between terms. Right now, it says "and" after every term, even it's only one term.
I know my problem lies within here:

<?php $terms = get_terms('department');
    foreach ( $terms as $term ) {
        echo $term->name.' and ';
    }
?>

How do I only get the "and" to only show between terms and not after every term?

1 Answer 1

0

If you need just the term names, fetch just the term names: use the field parameter for get_terms().

Build a comma separated list with an and between the last two items with wp_sprintf_l().

// get the term names
$term_names = get_terms( 'department', array ( 'fields' => 'names' ) );
// glue the names with comma and an 'and' between the last two
if ( ! empty ( $term_names ) )
    echo wp_sprintf_l( '%l', $term_names );
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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