A Comprehensive Guide to WordPress Plugin Development: From Scratch to Publishing Your Plugin

3-minute read
2026-03-19
2026-06-03
2,444
I earn commissions when you shop through the links below, at no additional cost to you.

Preparatory work and environment setup

Before starting to write any code, you need to make sure you have the correct development environment. This not only improves efficiency but also lays the foundation for releasing high-quality plugins.

First of all, you need a local or remote server environment that supports WordPress. It is recommended to use local development tools such as Local by Flywheel, XAMPP, or MAMP, which can quickly set up PHP, MySQL, and a web server for you. The core code for WordPress can be downloaded from its official website.

You will need a code editor or an integrated development environment (IDE), such as Visual Studio Code, PhpStorm, or Sublime Text. These tools offer features like syntax highlighting, code completion, and debugging, which are essential for development.

Recommended Reading Complete Guide to WordPress Plugin Development: Building Your First Functional Plugin from Scratch

Finally, it is highly recommended to create a version control system repository, such as on GitHub or GitLab. Even if your plugin is very small, using Git for version control can help you track changes, collaborate on its development, and make it easier to submit your plugin to the official WordPress plugin directory in the future.

UltaHost WordPress Hosting
30-day refund guarantee, unlimited bandwidth and database usage, free DDoS protection; purchase for 3 years and get a discount of 50%.

Create the first plug-in file

All WordPress plugins are stored in… wp-content/plugins It’s located in the directory. A plugin can be either a single file or a directory that contains multiple files. The most basic approach is to start with a single file.

Write the header information for the plug-in

Every WordPress plugin must contain a specific PHP comment block in its main file, known as the “plugin header.” WordPress uses this information to identify and display your plugin in the administration panel. The most basic plugin header must include the name of the plugin.

<?php
/**
 * Plugin Name:       我的第一个插件
 * Plugin URI:        https://example.com/my-first-plugin
 * Description:       这是一个简短的描述,说明这个插件是做什么的。
 * Version:           1.0.0
 * Author:            你的名字
 * Author URI:        https://example.com
 * License:           GPL v2 or later
 * Text Domain:       my-first-plugin
 * Domain Path:       /languages
 */

This comment defines the basic identity of the plugin.Plugin Name It is necessary; other information such as the version number and the text fields are also important for the release process. Save this file as… my-first-plugin.php And place it in… plugins In the directory, you can find it on the Plugins page in the WordPress administration panel and activate it.

Create a simple feature.

After activating the plugin, it currently doesn’t have any functionality. Let’s add a simple feature, such as adding a line of text to the website’s footer. This will require the use of a core WordPress action hook.

Recommended Reading A Complete Guide to WordPress Plugin Development: From Beginner to Expert in Building Custom Features

// 这个函数用于输出自定义文本
function my_first_plugin_add_footer_text() {
    echo '<p style="text-align: center;">Thank you for using my first plugin!</p>';
}
// 将上面的函数挂载到 WordPress 的 wp_footer 钩子上
add_action( 'wp_footer', 'my_first_plugin_add_footer_text' );

Place the code below the comments at the beginning of the plugin file. After saving the file, refresh your website’s front end, and you should see this text at the bottom of the page. With this example, you have already started using WordPress’s hook system to extend its functionality.

Core Development: Hooks and Filters

The core of WordPress plugin development is the Hook mechanism, which allows you to insert your own code at specific times or locations. There are two types of hooks: Actions and Filters.

Using action hooks

Action hooks allow you to execute functions at specific points in the WordPress lifecycle. The example mentioned earlier, which involved adding text to the footer, made use of action hooks. wp_footer Action. Another commonly used hook is… initIt is triggered during the WordPress initialization process and is commonly used for registering custom post types or taxonomies.

hosting.com Shared Hosting
High performance with AMD EPYC CPUs, NVMe SSD storage and LiteSpeed, 24/7, 24x7 expert in-house support, advanced security measures including SSL, brute force, malware and DDoS protection, savings of up to 73%
function my_plugin_custom_init() {
    // 在这里执行初始化代码
    error_log('我的插件已随 WordPress 初始化!');
}
add_action( 'init', 'my_plugin_custom_init' );

Understanding and making good use of action hooks is key to the deep integration of plugins with the WordPress core.

Use filters to modify the content.

Filter hooks allow you to modify the data that WordPress generates during its processing. For example, if you want to change the text that appears before an article title, you can use a filter hook to achieve this. the_title Filters.

function my_plugin_modify_title( $title, $id = null ) {
    // 只在主循环和单篇文章页为标题添加前缀
    if ( in_the_loop() && is_single() ) {
        return '【推荐】' . $title;
    }
    return $title;
}
add_filter( 'the_title', 'my_plugin_modify_title', 10, 2 );

Here 10 This is the default priority setting.2 This indicates that the filter function accepts two parameters. Using this filter, you can safely modify almost all the content that is generated by WordPress.

Recommended Reading From Zero to One: A Step-by-Step Guide to Mastering the Core Skills of WordPress Plugin Development

Plugin Structure and Advanced Features

As you start adding more features, it becomes difficult to maintain the code when all of it is contained in a single main file. A well-structured organization of the code is a standard in professional plugin development.

Organizing files and directories

A well-structured plugin directory might look like the following:

InterServer Shared Hosting
Shared hosting $2.50 USD per month , first month $0.1 USD promo code tryinterserver, 461 cloud apps scripts, one click install.
my-advanced-plugin/
├── my-advanced-plugin.php      // 主插件文件,包含头部和引导代码
├── includes/                   // 主要 PHP 类或函数文件目录
│   ├── class-admin-settings.php
│   ├── class-public-handler.php
├── admin/                     // 仅后台相关文件
│   ├── css/
│   ├── js/
│   └── views/
├── public/                    // 仅前台相关文件
│   ├── css/
│   ├── js/
│   └── views/
├── assets/                    // 共享资源(如图标)
└── languages/                 // 国际化翻译文件

In the main plugin file, you only need to be responsible for loading these sub-files. You can use… require_once Or include_once Use statements to introduce them. This structure makes the code more modular, which facilitates teamwork and long-term maintenance.

Create a management page.

Many plugins require a backend configuration page. WordPress provides functions for adding top-level or sub-menu pages. Below is an example of how to add a top-level menu page.

function my_plugin_add_admin_menu() {
    add_menu_page(
        '我的插件设置',    // 页面标题
        '我的插件',        // 菜单标题
        'manage_options', // 权限 capability
        'my-plugin-slug', // 菜单 slug
        'my_plugin_settings_page', // 用于渲染页面的回调函数
        'dashicons-admin-generic', // 图标
        80                  // 菜单位置
    );
}
add_action( 'admin_menu', 'my_plugin_add_admin_menu' );

function my_plugin_settings_page() {
    // 检查用户权限
    if ( !current_user_can( 'manage_options' ) ) {
        wp_die( __( '你没有足够的权限访问此页面。' ) );
    }
    ?&gt;
    <div class="wrap">
        <h1></h1>
        <form action="/en/options.php/" method="post" data-trp-original-action="options.php">
            <?php
            // 输出设置字段和安全密钥
            settings_fields( 'my_plugin_options_group' );
            do_settings_sections( 'my-plugin-slug' );
            submit_button();
            ?>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

This code will add a new menu item to the WordPress backend sidebar; clicking on that menu item will load a page containing a settings form. For it to function properly, you will also need to use the Settings API to register the settings fields and options.

Internationalization and Security Practices

Before releasing a plugin to a wider audience, it is crucial to ensure that it complies with the best practices for internationalization and security.

Plugin Internationalization

Internationalization (i18n) allows your plugin to be translated into other languages. You need to use the localization functions provided by WordPress. It is best practice to incorporate support for internationalization from the very beginning of your plugin development.

首先,确保在插件头部定义了 Text Domain and Domain PathThen, replace all user-facing strings with… ()_e() Or esc_html() These functions are wrapped in corresponding wrappers.

// 在插件代码中
echo '<p>' . esc_html__( '这是一个可以被翻译的段落。', 'my-first-plugin' ) . '</p>';

After that, use tools such as Poedit to create the necessary files. .pot Template files: Translators can use these to create content in various languages. .po and .mo Translate the file and place it in the location that was defined earlier. /languages Under the directory.

Enhancing the security of plugins

Security cannot be ignored. The core principles are: validating user input, escaping output data, and performing permission checks.
1. 验证与检查权限:任何处理用户数据或后台请求的函数,都必须检查当前用户是否有权执行该操作。使用 current_user_can() and check_admin_referer() Functions such as...
2. 转义输出:在将任何数据(尤其是来自用户或数据库的数据)输出到 HTML、JavaScript 或 URL 时,必须进行转义。
- HTML: esc_html(), esc_attr()
- URL: esc_url()
- 仅在 JavaScript 中:wp_json_encode()
3. 数据库安全:与 WordPress 数据库交互时,永远不要手动拼接 SQL 查询。使用 $wpdb Preparation statements.

    global $wpdb;
    $results = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}my_table WHERE id = %d AND status = %s",
            $user_id,
            $status
        )
    );

Testing and submitting to the official directory

After completing the development and basic testing locally, you need to conduct a comprehensive verification on a test site that simulates the user environment.

Use a version control system to create a formal release version of your plugin. Typically, you need to create a compressed package for your plugin as well. readme.txt The file must be in a format that meets the official WordPress requirements and should include information about the plugin, instructions for use, installation steps, and update logs. This file is crucial for the plugin to be displayed on WordPress.org.

When you are ready to submit your plugin to the official WordPress plugin directory, you will need to have a WordPress.org account. The submission process must follow the community guidelines to ensure that the code is of high quality, secure, and free from any malicious content. Once your plugin is approved, users around the world will be able to search for and install it. Remember that you also need to ensure that your plugin is compatible with the latest versions of WordPress. readme.txt The file and a suitable one… svn Use the repository structure to manage the versions of your plugins.

summarize

WordPress plugin development is a process that begins with understanding the basic structure of WordPress, gradually progresses to utilizing the hook system, organizing code in a modular manner, and strictly adhering to security and internationalization standards. Every step—from creating a simple file to building a complex plugin with management pages—relies on a deep understanding of the WordPress core architecture and the developer community. Following best practices not only makes your plugin more stable and secure but also simplifies future maintenance tasks and opens the door to the global WordPress user market. Continuously learning from the official documentation and studying the source code of high-quality plugins is key to continuously improving your development skills.

FAQ Frequently Asked Questions

What basic knowledge is required to develop WordPress plugins for ###?
You need to have a basic understanding of the PHP programming language, as the WordPress core and its plugins are primarily written in PHP. A basic knowledge of HTML, CSS, and JavaScript is also very helpful for creating user interfaces and interactive features. In addition, understanding the basic concepts of WordPress, such as themes, hooks, loops, and the template hierarchy, will make the development process smoother.

What files must a plugin include?

The most basic plugins only require a main PHP file that contains valid WordPress plugin header information. However, for any plugin that is a bit more complex, it is recommended to adopt a modular structure, separating different functions into separate files. For example, you can store the backend logic, frontend logic, resource files, and internationalization files in their respective directories. This improves the readability and maintainability of the code.

How can I add settings options for my plugin?

It is recommended to use the WordPress Settings API to add settings options. This includes utilizing the functionality provided by the API to manage and configure various settings within the WordPress system. register_setting() Register an option and use it. add_settings_section() and add_settings_field() Define the settings area and fields, and use them in the callback functions on the plugin’s backend menu page. settings_fields() and do_settings_sections() The form is generated accordingly. Although form submissions can also be processed manually, the Settings API takes care of data validation, storage, and security checks automatically.

How can I ensure that my plugin is compatible with other plugins or themes?

To achieve the highest level of compatibility, always use the APIs and functions provided by WordPress itself. Avoid using deprecated functions or directly modifying core files. Add a unique prefix to your functions, classes, and constants to prevent naming conflicts with other code. When saving settings or creating database tables, use the correct table prefixes. Additionally, when performing any operations that may affect the global state of the WordPress system, consider providing filter hooks so that other developers can customize the behavior of your plugin.

Does my plugin need to support the WordPress multi-site mode?

It depends on the functionality of your plugin. If your plugin operates on data related to the site (such as articles or options), by default, it will run independently on each site within a multi-site network, and this is usually not a problem. However, if your plugin requires the addition of network-level settings or management features, you will need to specifically check whether it is compatible with a multi-site environment and use appropriate mechanisms to ensure proper functionality across all sites. is_multisite()get_current_blog_id() Network-related functions (such as) add_network_option()To ensure that everything works properly, it’s a good habit to consider multi-site compatibility during the development phase.