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="https://www.xrbk.cn/1725.html#render_a8943f9c23f85f7fea498558b8e34ddd#' . $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' );
结语
功能不是很完善,但是可以显示了,需要其他功能自己添加
阅读剩余
THE END