1

Based on a few references I've built a function to output a list of custom taxonomy terms separated by comma. The code works as intended, where food_tag is the custom taxonomy I registered for a custom post_type.

Here's the function:

function get_taxonomy_food_tags(){
 $terms = get_terms('food_tag');
 foreach($terms as $term){

 // The $term is an object, so we don't need to specify the $taxonomy.

 $term_link = get_term_link($term);

 $numItems = count($terms);
 $i        = 0;

 // If there was an error, continue to the next term.

 if (is_wp_error($term_link)){
      continue;
 }

 // We successfully got a link. Print it out.

 echo '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';

 if (++$i != $numItems) {
            echo ', ';
 }

 }
}

I then place the code <?php get_taxonony_food_tags(); ?> anywhere in my theme's .php templates and I get a list of my custom tags with a link. such as:

Ingredients: Bacon, Tomato Slices, Tomato Sauce, Lettuce, Beef,

It turns out the last tag in the array is also printed with a comma

How do I properly set up the function to exclude the last comma?

Thanks in advance.

2

You have a couple of flaws here:

  • ALWAYS code in a way with a mindset of that your code will fail. This is very important. Most people code with a perfect world mindset. A perfect world will never happen. Always think of what will happen when your code fail.

    As example, in your code, $terms return an object of term objects if everything pans out. $terms also returns an empty array if there are no terms in the taxonomy or terms without having any posts. It also returns a WP_Error object if the taxonomy does not exist. This is all bugs. Invalid taxonomy you may ask. If you have correctly registered your taxonomy in a plugin, and you disable that plugin, your taxonomy does not exist anymore, which will trigger the invalid taxonomy error.

  • You should start your counter outside your foreach loop. Not inside

  • The get_ prefix is used for functions that returns its output, not echo it.

  • Always sanitize and validate

I will rewrite your code to look something like this: (NOTE: Requires PHP5.4 +)

function get_taxonomy_food_tags( $taxonomy = '', $args = [] )
{
    // Check if we have a taxonomy and that it is valid. If not, return false
    if ( !$taxonomy )
        return false;

    // Sanitize the taxonomy input
    $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );

    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    // If we reached this point, our taxonomy is valid. So lets continue. Get our terms
    $terms = get_terms( $taxonomy, $args );

    // We will only check if we have terms, we know our taxonomy is valid because we have reached this point
    if ( empty( $terms ) )
        return false;

    // Great, if we got to this point, we have terms, lets continue
    // Define our variable to hold our term links
    $term_links_array = [];
    foreach ( $terms as $term ) {
        $term_link = get_term_link( $term );

        // Make sure we do not have a WP_Error object, not really necessary, but better be safe
        if ( is_wp_error( $term ) )
            continue;

        // Build an array of term links. Let php do the hard work and calculations
        $term_links_array[] = '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';
    } // endforeach

    // Make sure that we have an array of term links, if not, return false
    if ( !$term_links_array )
        return false;

    // We have reached this point, lets output our term links
    return implode( ', ', $term_links_array );
}

You can now use it as follow

echo get_taxonomy_food_tags( 'food_tag' );

I have also introduced a second parameter which you can use to pass an array of arguments to the internal get_terms() function, so you can use the new function in the same exact way as the default get_terms() function

  • Amazing explanation and beautiful code rewriting! Thank you so much or your time! I've tested your code and it works perfectly. You've just described my very own scenario, as I'm managing the cpt through a very simple custom plugin that when deactivated was returning an error. I've learnt a bit more about php and WP, thanks again! – Adriano Monecchi Sep 4 '15 at 8:10
  • My pleasure. Glad you found this useful. Enjoy :-) – Pieter Goosen Sep 4 '15 at 8:31
1

The problem is you are giving 0 as a value to $i, every time the foreach loop executes, so, when the last if statement executes, every time the comparison is 1 != 3, and the comma will always be printed. Try to declare $i = 0; outside the foreach loop. Like this:

$terms = get_terms('food_tag');
$i = 0;
foreach($terms as $term){ 

//the code here

}

Also, there is a curly bracket missing at the end, maybe thats only a copy paste error, but for those who try to copy paste this and make it run.

  • Indeed declaring $i = 0; outside the foreach loop solves the last comma issue. The missing curly bracket is fixed. Thank you very much for your input. – Adriano Monecchi Sep 4 '15 at 8:04

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.