在 WordPress 的文章页侧边栏添加文章目录,只需将如下代码放到子主题的 function.php 文件中

class Article_TOC_Widget extends WP_Widget {

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

    public function widget( $args, $instance ) {
        global $post;
        if ( is_singular() && ! empty( $post->post_content ) ) {
            $toc = $this->get_toc( $post->post_content );
            if ( ! empty( $toc ) ) {
                echo $args['before_widget'];
                echo $args['before_title'] . '文章目录' . $args['after_title'];
                echo '<ul>' . $toc . '</ul>';
                echo $args['after_widget'];
            }
        }
    }

    public function get_toc( $content ) {
        $toc = '';
        $dom = new DOMDocument();
        @$dom->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) );
        $xpath = new DOMXPath( $dom );
        $headers = $xpath->query( '//h2|//h3|//h4|//h5|//h6' );
        if ( $headers->length > 0 ) {
            foreach ( $headers as $header ) {
                $id = $header->getAttribute( 'id' );
                if ( empty( $id ) ) {
                    $id = sanitize_title( $header->nodeValue );
                    $header->setAttribute( 'id', $id );
                }
                $toc .= '<li><a href="#' . $id . '">' . $header->nodeValue . '</a></li>';
            }
        }
        return $toc;
    }

}
function register_article_toc_widget() {
    register_widget( 'Article_TOC_Widget' );
}
add_action( 'widgets_init', 'register_article_toc_widget' );

这样一来就实现了所需要的功能,虽然不是很完善,但是可以显示了