如何获取WordPress自定义文章永久链接末尾段用于Fullpage.js的data-anchor
嘿,这个需求其实很好实现,我给你分享两种实用的方案,你可以根据自己的代码结构来选:
方案1:在WordPress文章循环里直接生成data-anchor
这是最直接的方式,在输出section的时候就处理好锚点值,不需要额外的JS操作。
假设你已经在模板里写了自定义文章类型的循环,只需要在生成section标签时,对文章永久链接做简单的字符串处理:
<?php // 自定义文章类型查询,替换成你的类型slug $args = array( 'post_type' => 'projects', 'posts_per_page' => -1 // 获取所有文章 ); $project_query = new WP_Query($args); if ($project_query->have_posts()) : while ($project_query->have_posts()) : $project_query->the_post(); // 获取文章永久链接 $permalink = get_permalink(); // 提取最后一段:先去掉首尾斜杠,分割成数组后取最后一个元素,再补回斜杠 $cleaned_link = trim($permalink, '/'); $link_parts = explode('/', $cleaned_link); $anchor_value = '/' . end($link_parts) . '/'; ?> <!-- 输出带data-anchor的section --> <section data-anchor="<?php echo esc_attr($anchor_value); ?>"> <h2><?php the_title(); ?></h2> <?php the_content(); ?> </section> <?php endwhile; wp_reset_postdata(); endif; ?>
这里的关键细节:
- 用
trim($permalink, '/')去掉链接首尾的斜杠,避免分割后出现空数组元素 end($link_parts)直接取数组最后一项,也就是你要的painting部分esc_attr()是WordPress的安全函数,确保输出的属性值不会有XSS风险
方案2:用JavaScript动态添加data-anchor
如果不想改动PHP循环代码,也可以等页面渲染完成后,用JS来补全属性值。
首先,确保每个section能关联到对应的文章永久链接——可以在渲染section时先加一个临时属性:
<section data-post-permalink="<?php echo esc_attr(get_permalink()); ?>"> <!-- 文章内容 --> </section>
然后在Fullpage初始化前执行JS处理:
document.addEventListener('DOMContentLoaded', function() { // 获取所有section元素 const sections = document.querySelectorAll('section[data-post-permalink]'); sections.forEach(section => { const permalink = section.dataset.postPermalink; // 提取最后一段锚点值 const linkParts = permalink.split('/').filter(part => part !== ''); const anchor = '/' + linkParts.pop() + '/'; // 给section添加data-anchor属性 section.setAttribute('data-anchor', anchor); }); // 初始化Fullpage.js new fullpage('#fullpage', { // 你的Fullpage配置项 }); });
额外提醒
- Fullpage.js要求
data-anchor的值必须唯一,所以要确保你的自定义文章类型的slug没有重复(WordPress默认会自动处理重复slug,比如加-2后缀,一般不用担心) - 两种方案都优先保证输出的锚点格式是
/xxx/,完全符合你需要的效果
内容的提问来源于stack exchange,提问作者Alexander Pauwelyn
相关产品推荐
相关产品推荐

