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 aWP_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