使类别词单独出现在 ACF 上
Make category words appear separately on ACF
我正在使用 ACF 分类子字段。我正在寻找一种方法来显示该字段中的多个类别。我正在使用的代码显示所有类别,但单词相互接触,并且不分开。
如何让那些分类词单独出现?
<?php
$term = get_sub_field('categories');
if( $term ) {
foreach($term as $t) {
$t = get_category($t);
echo $t->name;
}
}
?>
您只需要 concatenate 一个 space 到您的类别名称。您可以通过多种方式实现这一目标。
最简单的方法是:
<?php
$term = get_sub_field('categories');
if ($term) {
foreach ($term as $t) {
$t = get_category($t);
echo $t->name . ' ';
}
}
This way concatenates a space ' '
after each element. So your string will end up with a final space (also called trailing whitespace). This may be an issue or maybe not.
另一种方式:
<?php
$term = get_sub_field('categories');
if ($term) {
$first = true;
foreach ($term as $t) {
$t = get_category($t);
echo ($first ? '' : ' ') . $t->name;
$first = false;
}
}
This time we use a boolean $first
variable and the ternary operator Shorthand If/Else to concatenate the space before each element except the first one. This way your HTML code gets a clean string (without trailing spaces).
另一种获得干净字符串的方法是:
<?php
$term = get_sub_field('categories');
if ($term) {
$cats = [];
foreach ($term as $t) {
$t = get_category($t);
$cats[] = $t->name;
}
echo implode(' ', $cats);
}
In this example we push
all category names to $cats
array to finally convert (and echo
) this array to string with implode
.
希望对您有所帮助! :)
我正在使用 ACF 分类子字段。我正在寻找一种方法来显示该字段中的多个类别。我正在使用的代码显示所有类别,但单词相互接触,并且不分开。 如何让那些分类词单独出现?
<?php
$term = get_sub_field('categories');
if( $term ) {
foreach($term as $t) {
$t = get_category($t);
echo $t->name;
}
}
?>
您只需要 concatenate 一个 space 到您的类别名称。您可以通过多种方式实现这一目标。
最简单的方法是:
<?php
$term = get_sub_field('categories');
if ($term) {
foreach ($term as $t) {
$t = get_category($t);
echo $t->name . ' ';
}
}
This way concatenates a space
' '
after each element. So your string will end up with a final space (also called trailing whitespace). This may be an issue or maybe not.
另一种方式:
<?php
$term = get_sub_field('categories');
if ($term) {
$first = true;
foreach ($term as $t) {
$t = get_category($t);
echo ($first ? '' : ' ') . $t->name;
$first = false;
}
}
This time we use a boolean
$first
variable and the ternary operator Shorthand If/Else to concatenate the space before each element except the first one. This way your HTML code gets a clean string (without trailing spaces).
另一种获得干净字符串的方法是:
<?php
$term = get_sub_field('categories');
if ($term) {
$cats = [];
foreach ($term as $t) {
$t = get_category($t);
$cats[] = $t->name;
}
echo implode(' ', $cats);
}
In this example we
push
all category names to$cats
array to finally convert (andecho
) this array to string withimplode
.
希望对您有所帮助! :)