• I have the following code:

    <?php $terms = get_the_terms( $post->ID , 'writer' );
    if($terms) {
    	foreach( $terms as $term ) {
    		echo $term->name;
    	}
    }
    ?>

    I need to output my terms as a comma-separated list with the last term being preceded by an ampersand rather than a comma. So I want something like this: Author 1, Author 2 & Author 3

    For a complicated reason I won’t waste your time with, I can’t rely on CSS to do this, so I need an alternative.

Viewing 9 replies - 1 through 9 (of 9 total)
  • Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    So at the moment you know how to output commas?

    Thread Starter Rose

    (@eos-rose)

    I think I could use the implode function somehow to do that? I haven’t tried it yet, since that’s not what I’m really going for.

    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    If you’re just echoing the terms can’t you also just echo a comma?

    Thread Starter Rose

    (@eos-rose)

    My actual code includes a bit more than this, I just shared the basic idea.

    And if you just echo a comma in each loop, that means there will be (a) a hanging, unneeded comma at the end of the string, and (b) no ampersand.

    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    Untested but try this;

    <?php $terms = get_the_terms( $post->ID , 'writer' );
    if($terms) {
    	$i = 1;
    	foreach( $terms as $term ) {
    		echo $term->name;
    
    		if ( $i > 1 ) {
                            if ( $i != ( count( $terms ) - 1 ) && $i != ( count( $terms ) ) {
    		 		echo ', ';
                            }
    			else {
    				echo ' & ';
    			}
    		}
    
    		$i++;
    
    	}
    }
    ?>

    Thread Starter Rose

    (@eos-rose)

    The ampersand appears after the last term, when it should precede it.

    Thread Starter Rose

    (@eos-rose)

    I tried this:

    <?php $terms = get_the_terms( $post->ID , 'writer' );
    if($terms) {
    	$i = 1;
    	foreach( $terms as $term ) {
    		if ( $i > 1 ) {
    			if ( $i != ( count( $terms ) - 1 ) && $i != ( count( $terms ) ) ) {
    				echo ', ';
    			}
    			else {
    				echo ' & ';
    			}
    		}
    		echo $term->name;
    		$i++;
    	}
    }
    ?>

    The separator appears in the right place, but they are ALL ampersands, no commas.

    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    You need to modify this:

    if ( $i != ( count( $terms ) - 1 ) && $i != ( count( $terms ) ) ) {

    To check if it’s not the last or second from last item.

    Thread Starter Rose

    (@eos-rose)

    Modify how?

Viewing 9 replies - 1 through 9 (of 9 total)
  • The topic ‘Foreach loop seperated by commas, but last value preceded by amperstand’ is closed to new replies.