You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

foreach循环获取分类法ACF字段 修复前后分类取值异常

问题原因

上下分类链接无法读取对应ACF颜色值,核心是代码存在3个问题:

  • 两处颜色取值都传入了$tax变量,这个变量是foreach循环匹配到当前浏览分类后break留存的当前分类对象,不管上一个还是下一个链接,取到的永远是当前分类的颜色
  • 原有上下分类的边界判断逻辑错误,判断末尾分类跳回首项的条件写反,会导致列表末尾的跳转失效
  • 输出字段和链接时没做转义处理,特殊字符可能引发页面渲染异常,也没有配置颜色兜底值,未配置字段的分类会出现边框样式丢失
修复后代码

直接替换原有函数全部内容即可:

function next_prev_cat() {
    $this_taxonomy = get_queried_object();
    $current_tax_slug = '';

    if (is_category()) {
        // 过滤无内容的空分类,避免跳转项异常
        $taxonomies = get_categories(array(
            'hide_empty' => true,
        ));
        $current_tax_slug = 'category';
    }
    if (is_tag()) {
        $taxonomies = get_tags(array(
            'hide_empty' => true,
        ));
        $current_tax_slug = 'post_tag';
    }

    $total_tax = count($taxonomies);
    $current_pos = 0;
    // 遍历定位当前分类的排序位置
    foreach ($taxonomies as $position => $tax) {
        if ($this_taxonomy->term_id == $tax->term_id) {
            $current_pos = $position;
            break;
        }
    }

    // 用取模运算修正边界判断,自动实现首尾循环跳转
    $prev_pos = ($current_pos - 1 + $total_tax) % $total_tax;
    $next_pos = ($current_pos + 1) % $total_tax;

    // 提前取出上、下分类的完整 term 对象
    $prev_term = $taxonomies[$prev_pos];
    $next_term = $taxonomies[$next_pos];

    // 分别读取两个分类对应的ACF颜色值,加默认兜底色#333,可按需替换
    $prev_color = get_field('brand_colour', $prev_term) ?: '#333';
    $next_color = get_field('brand_colour', $next_term) ?: '#333';

    // 生成跳转链接
    $prevLink = get_term_link($prev_term);
    $nextLink = get_term_link($next_term);
    ?>
    <div class="area-links">
        <a style="border:1px solid <?php echo esc_attr($prev_color); ?>" href="<?php echo esc_url($prevLink); ?>"><?php echo esc_html($prev_term->name); ?></a>
        <a style="border:1px solid <?php echo esc_attr($next_color); ?>" href="<?php echo esc_url($nextLink); ?>"><?php echo esc_html($next_term->name); ?></a>
    </div>
    <?php
}
补充说明
  • ACF读取术语自定义字段时,直接传入对应WP_Term对象是官方兼容的标准写法,比拼接分类标识_术语ID的写法适配性更强,不会因为分类法自定义出现取值失败
  • 代码中新增的esc_attr/esc_url/esc_html是WordPress官方推荐的输出转义函数,可避免特殊字符导致的样式、链接失效问题
  • 如果不需要首尾循环跳转,只需要在计算完$prev_pos/$next_pos后加判断,超出范围时不输出对应链接即可

内容的提问来源于stack exchange,提问作者MattHamer5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 23:42:18