最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Sep 24, 2019 at 10:58 PetePete 1,0582 gold badges14 silver badges40 bronze badges 2
  • What is it you have now and what is the desired result? You can add a seperator via CSS also. Just add a border-left of border-right. – Refilon Commented Sep 24, 2019 at 11:30
  • @Refilon That's not a true separator as it will occur outside the terms. A separator only appears within the terms. – Pete Commented Sep 24, 2019 at 11:56
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布评论

评论列表(0)

  1. 暂无评论