我试图显示事件生产者的列表,这些生产者存储为分类法。对于每个事件(自定义帖子类型),可以有1到多个生产者,所以我想列出它们,用逗号分隔,并带有“&;”在倒数第二个和最后一个之间。除了只有一个制作人的情况外,以下函数完成此工作。我该如何让这一点同时适用于一个制片人或多个制片人?
function the_producers($post_id = false) {
if ($post_id == false) {
$post_id = get_the_ID();
}
$producers = get_the_terms($post_id, \'producers\');
$prods = array();
foreach ($producers as $producer) {
$prods[] = $producer->name;
}
$str = array_pop($prods);
if ($prods) {
$str = implode(\', \', $prods).\' & \'.$str;
return $str;
} else {
return false;
}
}
我尝试计算迭代次数,如果只有1次,只返回单个生产者,但由于某种原因,这似乎没有显示任何内容:
function the_producers($post_id = false) {
if ($post_id == false) {
$post_id = get_the_ID();
}
$producers = get_the_terms($post_id, \'producers\');
$prods = array();
$cnt = 0;
foreach ($producers as $producer) {
$cnt++;
$prods[] = $producer->name;
}
if ($cnt == 1) {
$str = $producer->name;
} else {
$str = array_pop($prods);
if ($prods) {
$str = implode(\', \', $prods).\' & \'.$str;
return $str;
} else {
return false;
}
}
}
最合适的回答,由SO网友:Eckstein 整理而成
这很有效。Pieter Gossen的计数方法更好,所以我也实现了这一点:
function the_producers($post_id = false) {
if ($post_id == false) {
$post_id = get_the_ID();
}
$producers = get_the_terms($post_id, \'producers\');
$q = count($producers);
if( 1 == $q ) {
$str = reset($producers)->name;
return $str;
} elseif ($q > 1) {
$prods = array();
foreach ($producers as $producer) {
$prods[] = $producer->name;
}
$str = array_pop($prods);
if ($prods) {
$str = implode(\', \', $prods).\' & \'.$str;
return $str;
} else {
return false;
}
} else {
return false;
}
}