WordPress文章怎么快速方便的生成目录索引?WordPress文章目录索引怎么生成?

Wordpress2年前 (2022)发布 SUYEONE
800 0 0

WordPress中创建文章目录索引是一个方便读者快速导航长篇文章的好方法。以下是实现这一功能的步骤,主要通过编辑主题的`functions.php`文件和应用CSS样式来完成。

**一、实现方法**

首先,确保你的文章包含至少一个`

`标签,因为这些将被用作目录的条目。以下代码会自动检测并处理`

`标签,将其转换为可点击的目录链接:

“`php
function article_toc($content) {
$matches = array();
$toc_list = ”;
$regex = ‘/

(.*?)/im’;

if (preg_match_all($regex, $content, $matches)) {
foreach ($matches[1] as $index => $title) {
$content = str_replace($matches[0][$index], ‘

‘ . $title . ‘

‘, $content);
$toc_list .= ‘

  • ‘ . $title . ‘
  • ‘;
    }

    if (is_singular()) {
    $content = ‘

    文章目录
      ‘ . $toc_list . ‘

    ‘ . $content;
    }
    }

    return $content;
    }
    add_filter(‘the_content’, ‘article_toc’);
    “`
    这段代码会将文章内容中的每一个`

    `标签替换为带有唯一ID的`

    `标签,并生成一个对应的目录列表。如果是在单篇文章页面,它会在内容前面插入这个目录。

    **二、目录样式**

    接下来,我们需要为这个目录添加一些样式,使其更易于阅读和使用。以下是一个基本的CSS样式示例,你可以根据自己的需求进行调整:

    “`css
    #toc_title {
    font-size: 14px;
    text-align: center;
    line-height: 20px;
    color: #333;
    border-left: 3px solid #333;
    border-bottom: 1px dotted #ccc;
    }

    #fn_article_toc {
    position: fixed;
    left: 5px;
    top: 100px;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 3px;
    box-shadow: 0 0 2px #ccc;
    padding: 10px;
    }

    #fn_article_toc ul {
    padding: 0 !important;
    margin: 0 !important;
    }

    #fn_article_toc li {
    list-style: none;
    padding: 5px 0;
    width: 100%;
    text-indent: 1.6em;
    font-size: 12px;
    }
    “`
    这段CSS代码将创建一个固定在页面左侧的目录,具有清晰的标题和易于点击的链接。你可以根据你的网站设计调整颜色、位置和其他样式属性。

    将以上代码分别添加到你的WordPress主题的`functions.php`文件和`style.css`文件中,你的文章就应该有了一个美观且实用的目录索引了。

    © 版权声明

    相关文章

    暂无评论

    暂无评论...
    ☺一键登录开启个人书签等功能!