给WordPress网站文章添加目录、多级标题标记、标题锚点

笔者希望给 WordPress 文章添加目录多级标题标记标题锚点,以便于长文阅读

  • 目录指的是将文章所有标题根据层次关系列入目录内
  • 多级标题标记指的是可以根据图标判断当前是几级标题
  • 标题锚点指的是点击图标页面中心即可跳转到该标题

目录

首先对于目录,这就比较简单了,直接下载 WordPress 插件“简单的目录”(也就是“easy table of contents”)

image-20220226143001060

随后在设置中进行相应设置即可

image-20220226143045232

该插件会自动将文章中的标题列入目录中,效果如下

image-20220226142340099

然而这个目录有一点小问题,在文章需要密码时仍能完整显示出目录,不会将目录进行移除

要解决这个问题可以随后在服务器上找到 WordPress 站点目录,如笔者的是 /www/wwwroot/[站点文件名]

在目录底下找到 wp-content/themes/[WordPress使用的主题名称]/footer.php

</body> 之前添加以下代码

<?php
	if(post_password_required())
		echo '<script>document.getElementById("ez-toc-container").remove();</script>';
?>

即可在文章需要密码时将目录进行移除

多级标题标记和标题锚点

我们经常会在一些笔记网站看到多级标题标记标题锚点功能,如

image-20220226143224939

要想美观地添加多级标题标记,首先先自己准备1级至6级标题的图标,下述代码中的titleAnchorImgDirUrl 表示其路径

image-20220226142517837

随后在服务器上找到 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;
}

即可大功告成

image-20220226142401168

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值