


How to develop a WordPress plugin that automatically generates a table of contents
How to develop a WordPress plug-in that automatically generates a table of contents
As the content of blog posts becomes more and more abundant, improving the reading experience has become an important consideration. Automatically generating a table of contents is a common method to improve the reading experience. Develop a plug-in that automatically generates a table of contents on the WordPress platform to help readers quickly browse and navigate article content. This article will introduce how to develop a WordPress plug-in that automatically generates a table of contents, and provide relevant code examples for reference.
First, we need to register a new widget (Widget) in the WordPress plugin to display the table of contents in the article. The following is a simple registration example of a directory widget:
class AutoTOC_Widget extends WP_Widget { public function __construct() { parent::__construct( 'auto_toc_widget', '自动生成目录', array( 'description' => '在文章中自动生成目录' ) ); } public function widget( $args, $instance ) { // 在文章中显示自动生成的目录 } public function form( $instance ) { // 小部件设置表单 } public function update( $new_instance, $old_instance ) { // 更新小部件设置 } }
Next, we need to write code in the widget()
method of the widget to implement the logic of directory generation. First, we need to get the content of the article and use a regular expression to match all title elements. The following is an example code:
public function widget( $args, $instance ) { global $post; $post_id = $post->ID; $post_content = $post->post_content; // 正则表达式匹配所有标题元素 preg_match_all( '/<h([1-6])>(.*?)</h>/', $post_content, $matches, PREG_SET_ORDER ); $toc_items = array(); // 构建目录项数组 foreach ( $matches as $match ) { $toc_item = array( 'title' => $match[2], 'level' => $match[1], 'anchor' => sanitize_title( $match[2] ) ); $toc_items[] = $toc_item; } // 显示目录部件的HTML输出 }
In the above code, we use the preg_match_all()
function to match the title element in the article content, and store the matching results in $matches
array. We then iterate over the $matches
array and build an array of TOC items $toc_items
that contains the text, level, and anchor of the title.
Finally, we need to generate the HTML output in the widget()
method of the Table of Contents widget and display it in the article. The following is the code for an example:
public function widget( $args, $instance ) { global $post; $post_id = $post->ID; // 生成目录HTML输出 $output = '<div class="auto-toc">'; $output .= '<h2 id="instance-title">' . $instance['title'] . '</h2>'; $output .= '<ul>'; foreach ( $toc_items as $item ) { $output .= '<li><a href="#' . $item['anchor'] . '">' . $item['title'] . '</a></li>'; } $output .= '</ul>'; $output .= '</div>'; echo $output; }
In the above code, we use a foreach
loop to iterate through the catalog item array $toc_items
, generating the HTML output of the catalog . Each table of contents item is wrapped in a list item's <li>
tag and contains an anchor link that enables readers to click to navigate within the article to the corresponding title.
Finally, we can also add some setting options in the form()
method of the widget to allow users to customize the title displayed in the directory. The following is a simple sample code:
public function form( $instance ) { $title = isset( $instance['title'] ) ? $instance['title'] : '目录'; echo '<p>'; echo '<label for="' . $this->get_field_id( 'title' ) . '">标题:</label>'; echo '<input class="widefat" id="' . $this->get_field_id( 'title' ) . '" name="' . $this->get_field_name( 'title' ) . '" type="text" value="' . esc_attr( $title ) . '">'; echo '</p>'; }
In the above code, we use an input
form element to allow the user to enter a custom directory title. This value will be saved in the plugin's settings and used in the widget's widget()
method.
Through the above code example, we can develop a plug-in that automatically generates a table of contents based on the WordPress platform to help improve the reading experience of blog articles. Readers can quickly browse and navigate article content by clicking on links in the table of contents. Developing your own WordPress plug-in can be expanded and customized according to actual needs, bringing a better user experience to readers.
The above is the detailed content of How to develop a WordPress plugin that automatically generates a table of contents. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to Add Online Payment Function to WordPress Plugin With the rapid development of the e-commerce industry, adding online payment function to the website has become a critical need. For those who use WordPress as a website development platform, there are many ready-made plugins that can help them achieve this goal. This article will introduce how to add online payment functionality to WordPress plug-in and provide code samples for reference. Determine the payment interface Before adding the online payment function, you must first determine the payment interface to use. current city

How to use WordPress plug-in to implement email subscription function In today’s Internet age, email subscription function has become an indispensable part of website operation. Through the email subscription function, we can push the latest news, activities, offers and other information to users in a timely manner to enhance user stickiness and interactivity. In the WordPress website, we can implement the email subscription function by using plug-ins. The following will introduce how to use the WordPress plug-in to implement the email subscription function. Step 1: Choose the right plugin

How to Develop an Auto-Updating WordPress Plugin WordPress is a very popular open source content management system (CMS) with a rich plugin market to extend its functionality. To ensure that plugins are always up to date and secure, developers need to implement automatic updates. In this article, we’ll walk you through how to develop an auto-updating WordPress plugin and provide code examples to help you get started quickly. Preparation Before starting development, you need to prepare the following key steps: Create

How to use WordPress plug-ins to achieve instant query function WordPress is a powerful blog and website building platform. Using WordPress plug-ins can further expand the functions of the website. In many cases, users need to perform real-time queries to obtain the latest data. Next, we will introduce how to use WordPress plug-ins to implement instant query functions and provide some code samples for reference. First, we need to choose a suitable WordPress plug-in to achieve instant query

How to develop a WordPress plug-in that automatically generates project progress. In the process of project management, it is very important to understand the project progress. For users who use WordPress to build websites, being able to directly view project progress in the WordPress backend will greatly improve work efficiency. Therefore, it is very beneficial to develop a WordPress plugin that automatically generates project progress. This article describes how to develop such a plug-in and provides code examples. Plugin Overview The main functions of this plugin are

How to avoid Chinese garbled characters in WordPress requires specific code examples. In the process of using WordPress websites, many users will encounter the problem of Chinese garbled characters. Garbled Chinese characters will cause trouble for users when reading and browsing the website, and may also affect the user experience and search engine optimization of the website. In this article, we will introduce some methods to solve the Chinese garbled problem in WordPress and provide specific code examples. Set the database character set: First, make sure the database character set is set correctly to support the

UniApp implements quick application development and launch process analysis. Quick application is an application model based on the mobile phone hardware platform that can be run without installation. It has the advantages of fast loading speed, low resource usage, and good user experience, and has become a new trend in mobile application development. In UniApp, we can easily develop and publish quick applications. This article will introduce in detail the development and launch process of UniApp to implement quick applications, and provide relevant code examples. Create UniApp project First, we need to create a UniApp project

How to Use WordPress Plugins to Implement Instant Question Function WordPress is a powerful and popular blogging and website building tool. It provides many plug-ins that allow bloggers to customize and enhance the functionality of their blog according to their needs. One of the very useful features is Live Questions, which allows bloggers to interact with readers in real time and answer their questions. This article will introduce how to use a WordPress plug-in to implement the instant question function and provide code examples. Step 1: Install the Plugin First, in WordP
