Table of Contents
Table of Contents Settings
Home CMS Tutorial WordPress How to develop a WordPress plugin that automatically generates directory trees

How to develop a WordPress plugin that automatically generates directory trees

Sep 06, 2023 am 09:55 AM
wordpress plug-in development (plug-in development)

How to develop a WordPress plugin that automatically generates directory trees

How to develop a WordPress plug-in that automatically generates a directory tree

With the continuous development of WordPress websites, the scale of website content is also becoming larger and larger. It is very important for readers to be able to quickly navigate and browse the content of the website. The directory tree is a very useful feature that can help readers quickly locate and browse different parts of the website. This article will teach you how to develop a WordPress plug-in that automatically generates directory trees.

Before we start developing plug-ins, we need to understand the basic structure and principles of WordPress plug-ins. A WordPress plugin consists of a main plugin folder and one or more feature files. The main folder contains the plugin’s main file (usually a PHP file) and other required files (such as CSS and JavaScript files). The function file contains the code that implements the specific functions of the plug-in. Next, we will create a WordPress plugin that automatically generates directory trees step by step.

Step 1: Create the basic structure of the plug-in
First, we need to create a folder as the main folder of our plug-in. Give it a meaningful name, such as "table-of-contents". In this folder, we will create a main plugin file called "table-of-contents.php".

Open the "table-of-contents.php" file and add the following code to the file:

<?php
/**
 * Plugin Name: Table of Contents
 * Description: Automatically generates a table of contents for your WordPress posts and pages.
 * Version: 1.0.0
 * Author: Your Name
 * License: GPL2
 */

// 插件代码将在这里添加
?>
Copy after login

In the above code, we define the basic information of the plug-in, such as name, description , edition, author and license.

Step 2: Add the plug-in settings page
Now, we need to add a settings page for the plug-in to select which pages or articles to display the directory tree. In the "table-of-contents.php" file, add the following code:

// 激活插件时添加设置菜单
function toc_add_settings_menu() {
  add_options_page( 'Table of Contents Settings', 'Table of Contents', 'manage_options', 'table-of-contents-settings', 'toc_render_settings_page' );
}
add_action( 'admin_menu', 'toc_add_settings_menu' );

// 渲染设置页面
function toc_render_settings_page() {
  ?>
  <div class="wrap">
    <h1 id="Table-of-Contents-Settings">Table of Contents Settings</h1>
    <form method="post" action="options.php">
      <?php settings_fields( 'toc_settings_group' ); ?>
      <?php do_settings_sections( 'toc_settings_page' ); ?>
      <?php submit_button(); ?>
    </form>
  </div>
  <?php
}
Copy after login

In the above code, we create a settings page using the function add_options_page() provided by WordPress, And add its link to the "Settings" menu in the WordPress backend. We also created a function toc_render_settings_page() for rendering the settings page content.

Step Three: Add Setting Fields and Save Function
In the previous step, we created a settings page, but there are no settings fields on the page yet. Next, we'll add a checkbox field that selects which pages or posts we want the tree to display on. In the "table-of-contents.php" file, add the following code:

// 注册设置字段
function toc_register_settings() {
  register_setting( 'toc_settings_group', 'toc_display_options' );
  add_settings_section( 'toc_general_section', 'General Settings', 'toc_general_section_callback', 'toc_settings_page' );
  add_settings_field( 'toc_display_options_field', 'Display Options', 'toc_display_options_field_callback', 'toc_settings_page', 'toc_general_section' );
}
add_action( 'admin_init', 'toc_register_settings' );

// 渲染字段
function toc_display_options_field_callback() {
  $options = get_option( 'toc_display_options' );
  $pages = get_pages();
  foreach ( $pages as $page ) {
    $checked = isset( $options[$page->ID] ) ? checked( $options[$page->ID], $page->post_title, false ) : '';
    echo '<input type="checkbox" name="toc_display_options[' . $page->ID . ']" value="' . esc_attr( $page->post_title ) . '" ' . $checked . '> ' . esc_html( $page->post_title ) . '<br>';
  }
}

// 保存设置
function toc_save_settings() {
  if ( isset( $_POST['toc_display_options'] ) ) {
    $options = array();
    foreach ( $_POST['toc_display_options'] as $page_id => $title ) {
      $options[$page_id] = $title;
    }
    update_option( 'toc_display_options', $options );
  }
}
add_action( 'admin_post_save_toc_settings', 'toc_save_settings' );
Copy after login

In the above code, we use the register_setting() function to register a setting field, use ## The #add_settings_section() function creates a group of settings fields, and the add_settings_field() function creates a multi-select box field.

We also define a callback function that renders the settings field

toc_display_options_field_callback(), which displays all pages as multi-select box fields. We also define a function to save settings toc_save_settings(), in which we use the update_option() function to save the user-selected page to the WordPress database.

Step 4: Generate directory tree

Now that we have set up the basic structure and settings page of the plug-in, we will add the function of generating a directory tree. In the "table-of-contents.php" file, add the following code:

// 生成目录树
function toc_generate_toc() {
  $options = get_option( 'toc_display_options' );
  if ( $options ) {
    global $post;
    if ( isset( $options[$post->ID] ) ) {
      $content = apply_filters( 'the_content', $post->post_content );
      $pattern = "/<h([1-6])>(.*?)</h[1-6]>/";
      preg_match_all( $pattern, $content, $headings, PREG_SET_ORDER );
      $tree = array();
      foreach ( $headings as $heading ) {
        $level = intval( $heading[1] );
        $title = strip_tags( $heading[2] );
        $tree[] = array(
          'level' => $level,
          'title' => $title
        );
      }
      $toc_html = '<ul class="toc">';
      $current_level = 0;
      foreach ( $tree as $branch ) {
        if ( $branch['level'] == $current_level ) {
          $toc_html .= '</li><li>';
        } elseif ( $branch['level'] > $current_level ) {
          $toc_html .= '<ul>';
        } elseif ( $branch['level'] < $current_level ) {
          $toc_html .= '</li>';
          for ( $i = $branch['level']; $i < $current_level; $i++ ) {
            $toc_html .= '</ul></li>';
          }
          $toc_html .= '<li>';
        }
        $toc_html .= '<a href="#' . sanitize_title( $branch['title'] ) . '">' . esc_html( $branch['title'] ) . '</a>';
        $current_level = $branch['level'];
      }
      $toc_html .= '</li>';
      for ( $i = $current_level; $i > 0; $i-- ) {
        $toc_html .= '</ul></li>';
      }
      $toc_html .= '</ul>';
      return $toc_html;
    }
  }
}
add_shortcode( 'table_of_contents', 'toc_generate_toc' );
Copy after login

In the above code, we first get the pages selected by the user and generate a directory tree based on the content of these pages. We use a regular expression to match title tags on the page and store the matched titles in an array. Afterwards, we use loops to organize these titles hierarchically and sequentially into a directory tree.

We also use a shortcode

[table_of_contents] to call the toc_generate_toc() function and return the generated directory tree as the content.

Step 5: Add styles and scripts

In order to give the directory tree a better appearance and interactive effect, we need to add some styles and scripts. In the "table-of-contents.php" file, add the following code:

// 添加样式和脚本
function toc_enqueue_scripts() {
  wp_enqueue_style( 'toc-style', plugins_url( 'css/style.css', __FILE__ ) );
  wp_enqueue_script( 'toc-script', plugins_url( 'js/script.js', __FILE__ ), array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'toc_enqueue_scripts' );
Copy after login

In the above code, we used the functions

wp_enqueue_style() and wp_enqueue_script provided by WordPress () to load the style sheets and script files required by the plug-in. Note that we need to place the stylesheet and script files in the "css" and "js" subfolders of the plugin folder and add corresponding file names to them.

Step 6: Add the directory tree to the page or article

The last step is to add the generated directory tree to the page or article where you want to display the directory tree. When editing a page or post, you can use the shortcode
[table_of_contents] to insert a table of contents tree anywhere on the page. Please add the following code in the "table-of-contents.php" file:

<!-- 在编辑器中显示目录树短代码按钮 -->
<script>
  function add_toc_shortcode_button() {
    if ( typeof wp !== 'undefined' && wp.hasOwnProperty( 'shortcode' ) ) {
      wp.mce = wp.mce || {};
      wp.mce.tinymce = wp.mce.tinymce || {};
      wp.mce.views = wp.mce.views || {};

      wp.mce.tinymce.Template = Backbone.Marionette.ItemView.extend({});

      $( document ).on( 'click', 'a.add-toc-shortcode', function(e) {
        e.preventDefault();
        wp.mce.views.getParentWindow().send_to_editor('[table_of_contents]');
      });
    }
  }
  $(document).ready(function() {
    add_toc_shortcode_button();
  });
</script>
Copy after login
In the above code, we use JavaScript code to add a button to the editor, which can quickly insert

[table_of_contents] Shortcode into the editor.

Through the above six steps, we have developed a WordPress plug-in that automatically generates a directory tree. You can further modify and optimize the plug-in according to your own needs. I hope this article is helpful to you, and I wish you smooth development!

The above is the detailed content of How to develop a WordPress plugin that automatically generates directory trees. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

How much does WordPress cost? How much does WordPress cost? Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Why would anyone use WordPress? Why would anyone use WordPress? Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

Is WordPress a CMS? Is WordPress a CMS? Apr 08, 2025 am 12:02 AM

WordPress is a Content Management System (CMS). It provides content management, user management, themes and plug-in capabilities to support the creation and management of website content. Its working principle includes database management, template systems and plug-in architecture, suitable for a variety of needs from blogs to corporate websites.

Is WordPress still free? Is WordPress still free? Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

See all articles