如何在WordPress建站中创建目录?

玖比肆 WordPress 48

通过安装目录插件或编写自定义代码,您可以为WordPress建站的长篇文章添加目录功能,提高用户体验。

回复

共1条回复 我来回复
  • 玖比肆的头像
    玖比肆 评论

    以下是使用插件和编写代码两种方法来创建目录的步骤:

    1. 使用插件

    步骤一: 安装 TOC+(Table of Contents Plus)插件
    进入WordPress后台,点击左侧菜单的“插件”->“添加新插件”,在搜索框内输入 TOC+,然后安装并启用该插件。

    步骤二: 配置TOC+
    进入插件设置,调整插件的外观和行为,比如选择需要添加目录的文章类型、目录的放置位置、样式和缩进等,也可以自定义不同文章中目录的样式和显示方式,最后保存更改。

    2. 编写代码

    步骤一: 在functions.php文件中添加代码
    进入WordPress后台,点击“外观”->“编辑”->“functions.php”,将下面的代码复制到functions.php文件中(最好先备份原函数)。

    // add TOC to post content
    function add_toc_to_content( $content ) {
    $post_type = get_post_type();
    if ( $post_type == 'post' ) {
    if ( is_single() ) {
    $content = generate_toc( $content );
    }
    }
    return $content;
    }
    add_filter( 'the_content', 'add_toc_to_content', 100 );

    // generate TOC
    function generate_toc( $content ) {
    preg_match_all('/(.*?)/si', $content, $matches, PREG_SET_ORDER);
    $toc = '';
    $max_depth = 2; // define max depth of h tags
    $top_heading = 1; // define top level of heading

    if( $matches ){
    $count = array(0,0,0,0,0,0);
    $current_depth = 1;
    foreach( $matches as $match ){
    list($match_tag, $match_n, $match_title)=$match;
    if( $match_n <= $max_depth ){ // only handle h1 ~ h6 $count[$match_n] ++; for($i = $match_n+1 ;$i < 7;$i++){ // reset lower heading counter $count[$i]=0; } while($current_depth < $match_n ){ // add start of sub-list $toc .= "

      n";
      $current_depth++;
      }
      while($current_depth > $match_n){ // end sub-list
      $toc .= "n

    n";
    $current_depth--;
    $count[$current_depth]=0; // reset sub-counter
    $count[$current_depth-1]++;
    }
    $id = ' toc-' . $match_n . '-' . $count[$match_n]; // generate unique ID
    $toc .= '

  • ' . $match_title . "n"; // add anchor text
    $content = str_replace($match_tag,'<' . $match_tag . ' id="'. sanitize_title_with_dashes($match_title) . $id . '">' . $match_title . '',$content); // add ID to heading
    }
    }
    while($current_depth >= $top_heading){ // add closing tags
    $toc .= "
  • nn";
    $current_depth--;
    }
    }
    return $toc.$content;
    }

    步骤二: 编辑文章,插入TOC ID
    在需要添加目录的文章中插入HTML代码

    该 ID 将在函数中作为存储目录的容器,将在文章中生成目录。

    步骤三: 编辑CSS样式
    在主题或子主题的样式表中添加目录的样式,以确保目录在网站上显示完美。

2023年 4月 26日 下午4:32 0条评论
微信客服
分享本页
返回顶部
玖比肆(9Bi4)专注于帮助企业实现数字化转型,提供全方位的网站建设、网络运营、网络推广、网络营销和SEO优化等一系列数字化营销服务。