您需要获取直接父对象的颜色,或者循环遍历所有Ansestor,直到找到颜色为止
如果未找到颜色,则获取默认值并输出。
我对结构做了一些更改,并为每个步骤添加了所有注释。
请注意,为了获得相同的结果,我提供了两个选项,请选择一个适合您需要的选项。
// get category terms of the current post
if ($terms = get_the_terms( get_the_ID(),\'category\')) {
// prepare the output for sprintf
// to avoid repeating ourselves we can create a variable to conatin the output
// %s is a sting placeholder
$output = \'<div class="post_loop-cat" style="background-color: %s;">%s</div>\';
// unless you always have one categpry for every post
// this will always set $cat_id to the last $term of the loop, always
// take this into account
foreach ($terms as $term) {
$cat_id = $term->term_id;
}
// get ACF category color
$cat_color = get_field(\'category-color\', \'category_\' . $cat_id);
// because we don\'t know the depth of the category
// or how high do you want to go to get the parent color
// we can do either of the following
// in both options we will first check if $cat color exists
// option 1
// using the direct parent only
if ($cat_color) { // color found, output the html
echo sprintf($output, $cat_color, $term->name);
} else {
// get the parent category color
$cat_color = get_field(\'category-color\', \'category_\' . $term->parent);
// if not found, set color to default
if (empty($cat_color)) $cat_color = get_field(\'primary-color\', \'option\');
// output the html
echo sprintf($output, $cat_color, $term->name);
}
// option 2
// using the category ancestors to find the color
// we loop each ancestor, once we found a color we stop and output
if ($cat_color) { // color found, output the html
echo sprintf($output, $cat_color, $term->name);
} else {
// get and loop all ansestors
foreach (get_ancestors($cat_id, \'category\') as $ancestor_id) {
// get and check category color, if found, break out of the loop
if ($cat_color = get_field(\'category-color\', \'category_\' . $ancestor_id)) break;
}
// if not found, set color to default
if (empty($cat_color)) $cat_color = get_field(\'primary-color\', \'option\');
// output the html
echo sprintf($output, $cat_color, $term->name);
}
}
为了不重复输出,我使用了一个变量,稍后将与一起使用
sprintf, 单击链接了解更多信息
快速描述,sprintf创建格式化字符串。