
最近的一个wordpress外贸建站项目需要制作一个类似于文档页的页面,里面用来放一些使用说明、指南等内容,内容比较多,为了方便快速定位,我用到了Elementor编辑器中的Table of Contents模块。但是这个模块默认状态下的锚点链接格式为【页面网址#elementor-toc******】,感觉不是太友好。
所以我做了一些修改,让Table of Contents模块的锚点链接以H标题为URL后缀,这个会更容易理解。直接给出代码,大家可以按需使用,直接复制粘贴即可。
// 为内容里的 H 标题自动生成 ID(Elementor TOC 友好)
function add_custom_id_to_headings( $content ) {
if ( is_admin() ) return $content;
$pattern = '/(<h([1-6]))(.*?)>(.*?)<\/h\2>/is';
$content = preg_replace_callback( $pattern, function( $matches ) {
$tag_open = $matches[1]; // <h2
$level = $matches[2]; // 2
$attrs = $matches[3]; // 其他属性
$title_text = wp_strip_all_tags( $matches[4] );
// 已存在 id 就跳过
if ( stripos( $attrs, 'id=' ) !== false ) {
return $matches[0];
}
// 标题转 URL 友好格式
$anchor = sanitize_title( $title_text );
return $tag_open . $attrs . ' id="' . esc_attr( $anchor ) . '">' . $matches[4] . '</h' . $level . '>';
}, $content );
return $content;
}
add_filter( 'the_content', 'add_custom_id_to_headings', 999 );
// 强制 Elementor TOC 使用页面自带的 id
add_filter( 'elementor/toc/use_existing_anchor_ids', '__return_true' );
代码可以添加到主题或子主题的functions.php文件中,也可以添加到wp code等代码管理插件中。
代码应用之后,前端刷新浏览器或清空一下缓存即可生效。
© Copyright 2024. 悦然网络工作室/悦然wordpress建站 专注中小企业wordpress建站 All Rights Reserved.网站地图
本站图片来源为Pexels、Pixabay、Freepik、Unsplash等图片库的免费许可,CC0协议;还有部分为自己手绘,版权碰瓷请自重!法律服务:law@yueranseo.com 蜀ICP备20016391号-1 川公网安备 51011502000367号