笔者希望给 WordPress 文章添加目录、多级标题标记、标题锚点,以便于长文阅读
- 目录指的是将文章所有标题根据层次关系列入目录内
- 多级标题标记指的是可以根据图标判断当前是几级标题
- 标题锚点指的是点击图标页面中心即可跳转到该标题
目录
首先对于目录,这就比较简单了,直接下载 WordPress 插件“简单的目录”(也就是“easy table of contents”)
随后在设置中进行相应设置即可
该插件会自动将文章中的标题列入目录中,效果如下
然而这个目录有一点小问题,在文章需要密码时仍能完整显示出目录,不会将目录进行移除
要解决这个问题可以随后在服务器上找到 WordPress 站点目录,如笔者的是 /www/wwwroot/[站点文件名]
在目录底下找到 wp-content/themes/[WordPress使用的主题名称]/footer.php
在 </body>
之前添加以下代码
<?php
if(post_password_required())
echo '<script>document.getElementById("ez-toc-container").remove();</script>';
?>
即可在文章需要密码时将目录进行移除
多级标题标记和标题锚点
我们经常会在一些笔记网站看到多级标题标记和标题锚点功能,如
要想美观地添加多级标题标记,首先先自己准备1级至6级标题的图标,下述代码中的titleAnchorImgDirUrl
表示其路径
随后在服务器上找到 WordPress 站点目录,如笔者的是 /www/wwwroot/[站点文件名]
在目录底下找到 wp-content/themes/[WordPress使用的主题名称]/footer.php
在 </body>
之前添加以下代码(需要在已经添加了上述目录插件的基础上才能有效)
<script type="text/javascript">
//多级标题图标的路径
let titleAnchorImgDirUrl="img/";
var blogContentBox=document.getElementsByClassName("single-entry-summary")[0];
var titleAnchor=document.createElement("a");
var titleAnchorImg=document.createElement("img");
//给多级标题图标设置"blog-title-anchor"便于后续CSS调整样式
titleAnchorImg.setAttribute("class","blog-title-anchor");
titleAnchor.appendChild(titleAnchorImg);
for(i=0;i<blogContentBox.childNodes.length;i++){
makeAnchor(blogContentBox.childNodes[i]);
}
function makeAnchor(blogChildNode){
switch(blogChildNode.tagName){
case "H1":
case "H2":
case "H3":
case "H4":
case "H5":
case "H6":
let newTitleAnchor=titleAnchor.cloneNode(true);
newTitleAnchor.firstChild.setAttribute("src",titleAnchorImgDirUrl+blogChildNode.tagName+".png");//根据标题级别选择相应图标
newTitleAnchor.setAttribute("href","#"+blogChildNode.firstChild.getAttribute("id"));//设置跳转功能
blogChildNode.insertBefore(newTitleAnchor,blogChildNode.firstChild);
break;
default:
break;
}
}
</script>
再简单添加一点 CSS 样式
/*博客n级标题锚点*/
.blog-title-anchor{
width: 0.9em;
height: 0.9em;
margin-right:0.5em;
margin-bottom:0.2em;
cursor: pointer;
}
/*博客n级标题悬浮*/
.single-content h2:hover,
.single-content h3:hover,
.single-content h4:hover,
.single-content h5:hover,
.single-content h6:hover{
color:#686868DD;
transition: all 0.3s ease;
}
即可大功告成
更多推荐
给WordPress网站文章添加目录、多级标题标记、标题锚点
发布评论