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

WordPress中使用PHP循环实现ACF脚注ID自增与锚点关联的方法咨询

实现方案

1. 修改页脚脚注循环代码,添加自增计数器

在遍历脚注分组前初始化计数器,每输出一条脚注自动累加,动态生成对应的ID和跳转链接,修正后的完整代码如下:

<div id="footnotes" class="footnotes">
<?php if ( have_rows( 'footnotes' ) ) : ?>
    <?php while ( have_rows( 'footnotes' ) ) : the_row(); ?>
        <?php if ( have_rows( 'footnotes_group' ) ) : ?>
            <ol>
            <?php 
            // 初始化脚注自增计数器
            $footnote_index = 1; 
            while ( have_rows( 'footnotes_group' ) ) : the_row(); 
            ?>
                <li id="footnote-bottom-<?php echo $footnote_index; ?>">
                    <?php the_sub_field( 'footnotes_reference' ); ?>
                    <a href="#footnote-top-<?php echo $footnote_index; ?>">
                        <span class="screen-reader-text"><?php the_sub_field( 'footnotes_to_number' ); ?></span>
                        <?php the_sub_field( 'footnotes_to_top' ); ?>
                    </a>
                </li>
            <?php 
            // 计数器自增
            $footnote_index++; 
            endwhile; 
            ?>
            </ol>
        <?php else : ?>
            <?php // 无脚注内容 ?>
        <?php endif; ?>
    <?php endwhile; ?>
<?php else : ?>
    <?php // 无脚注分组 ?>
<?php endif; ?>
</div>

注意:原示例代码中的footnot-top、footnohte-bottom为拼写错误,已统一修正为footnote-top、footnote-bottom命名规则,避免锚点跳转失效。

2. 动态生成正文上标脚注

为了保证正文上标的ID和页脚脚注一一对应,推荐用WordPress短代码实现自动编号,避免手动编写ID出错。将以下代码添加到当前主题的functions.php文件中:

// 注册脚注上标短代码
add_shortcode('footnote', function($atts, $content = null) {
    static $footnote_count = 1;
    if (!$content) $content = $footnote_count;
    $output = sprintf(
        '<sup class="footnote" id="footnote-top-%d"><a href="#footnote-bottom-%d">%s</a></sup>',
        $footnote_count,
        $footnote_count,
        esc_html($content)
    );
    $footnote_count++;
    return $output;
});

之后在文章正文中需要插入脚注的位置,直接输入[footnote]即可自动生成对应编号的上标,ID和跳转链接会自动匹配页脚的脚注顺序。

3. 可选CSS优化跳转体验

添加以下CSS代码,实现平滑跳转,同时避免锚点被顶部固定导航遮挡:

/* 平滑滚动 */
html {
    scroll-behavior: smooth;
}
/* 锚点跳转偏移,可根据实际导航高度调整数值 */
:target::before {
    content: "";
    display: block;
    height: 80px;
    margin: -80px 0 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:54:00