How do I add a separator to my list of terms with get_category

I have this...

$args = array('child_of' = 3422 );
$categories = get_categories( $args );
foreach($categories as $category) { 
    echo 'a href="' . get_category_link( $category-term_id ) . '" title="' . sprintf( __( "View all members in %s" ), $category-name ) . '" ' . '' . $category-name.'/a '; 
}

I can't find a way to add a separator between each term?

Topic wp-parse-args list categories Wordpress

Category Web


With the code that you're using your just going to get a list of words that are links to the categories.

You are facing two problems, adding the separator and also making sure the separator isn't added to to the last item.

You have a couple options: With your code:

$args = array('child_of' => 3422 );
$categories = get_categories( $args );
$i = 1;
$separator = ', '; // Include a separator to separate the category
$count_category = count($categories);   // get total category value  to limit the separator for last
foreach($categories as $category) { 
    if ($i != 1) {
       echo $separator;
    }
    if($i< $count_category && $i!=1){
      echo '.';
    }
    echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all members in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> ';  
  $i++;
}

or you can do it using

get_the_category_list( string $separator = '', string $parents = '', int $post_id = false )

$args = array('child_of' => 3422 );
echo get_the_category_list (',' );

see more here on the developers page.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.