找回密码
 立即注册
搜索
热搜: 活动 交友
查看: 2295|回复: 0

WordPress文章页侧边栏添加文章目录

[复制链接]

32

主题

0

回帖

116

积分

管理员

积分
116
发表于 2024-12-18 11:44:02 | 显示全部楼层 |阅读模式
前言
不少主题都支持文章页的侧边栏添加文章目录的小工具
教程
将如下代码放到子主题的function.php中
  1. class Article_TOC_Widget extends WP_Widget {

  2.     public function __construct() {
  3.         parent::__construct(
  4.             'article_toc_widget',
  5.             '文章目录小工具',
  6.             array( 'description' => '在文章或页面的侧边栏中显示文章目录' )
  7.         );
  8.     }

  9.     public function widget( $args, $instance ) {
  10.         global $post;
  11.         if ( is_singular() && ! empty( $post->post_content ) ) {
  12.             $toc = $this->get_toc( $post->post_content );
  13.             if ( ! empty( $toc ) ) {
  14.                 echo $args['before_widget'];
  15.                 echo $args['before_title'] . '文章目录' . $args['after_title'];
  16.                 echo '<ul>' . $toc . '</ul>';
  17.                 echo $args['after_widget'];
  18.             }
  19.         }
  20.     }

  21.     public function get_toc( $content ) {
  22.         $toc = '';
  23.         $dom = new DOMDocument();
  24.         @$dom->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) );
  25.         $xpath = new DOMXPath( $dom );
  26.         $headers = $xpath->query( '//h2|//h3|//h4|//h5|//h6' );
  27.         if ( $headers->length > 0 ) {
  28.             foreach ( $headers as $header ) {
  29.                 $id = $header->getAttribute( 'id' );
  30.                 if ( empty( $id ) ) {
  31.                     $id = sanitize_title( $header->nodeValue );
  32.                     $header->setAttribute( 'id', $id );
  33.                 }
  34.                 $toc .= '<li><a href="https://www.xrbk.cn/1725.html#' . $id . '">' . $header->nodeValue . '</a></li>';
  35.             }
  36.         }
  37.         return $toc;
  38.     }

  39. }
  40. function register_article_toc_widget() {
  41.     register_widget( 'Article_TOC_Widget' );
  42. }
  43. add_action( 'widgets_init', 'register_article_toc_widget' );
复制代码
结语
功能不是很完善,但是可以显示了,需要其他功能自己添加

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【赶紧来试试吧】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|奥多也网络 ( 粤ICP备2020119241号 )

GMT+8, 2025-12-9 04:46 , Processed in 0.071710 second(s), 26 queries .

Powered by AODUOYE

©2017-2026

快速回复 返回顶部 返回列表