From Scratch: A Comprehensive Guide and Practical Tutorial for WordPress Plugin Development

3-minute read
2026-03-12
2026-06-04
2,459
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 code, a stable and efficient development environment is of paramount importance. This not only ensures that your plugin maintains a clear structure throughout future development but also allows you to leverage modern tools to improve your productivity.

Configuring the local development environment

We recommend using a local server environment, such as Local by Flywheel, XAMPP, or MAMP. These tools allow you to quickly set up a WordPress environment on your computer that includes Apache/Nginx, MySQL, and PHP. Make sure that your PHP version is compatible with the version of the server you will be using in production, and enable the error reporting feature; this will help you identify issues more quickly during the development phase.

Code Editor and Tool Selection

The first step is to choose a powerful code editor, such as Visual Studio Code, PhpStorm, or Sublime Text. These editors typically offer features like syntax highlighting, code suggestions, and integration with version control systems. Additionally, installing a code quality improvement tool (such as PHP_CodeSniffer) and a debugging tool (such as Xdebug) will greatly enhance your development experience and the quality of your code.

Recommended Reading WordPress Theme Development Complete Guide: Building Professional Websites from Scratch

Create your first plugin

Now, let’s start by creating the simplest plugin to understand the basic structure and activation mechanism of WordPress plugins.

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%.

Plugin main file and basic header information

Every WordPress plugin must have a main PHP file, and this file must contain the standard plugin header information so that WordPress can recognize it. Let’s create a file named… my-first-plugin.php The file.

Place the code in that file, and then upload it to the WordPress installation directory. /wp-content/plugins/my-first-plugin/ Inside the folder.

<?php
/**
 * Plugin Name:       我的第一个插件
 * Plugin URI:        https://example.com/my-first-plugin
 * Description:       这是一个用于学习的简单 WordPress 插件。
 * Version:           1.0.0
 * Author:            你的名字
 * Author URI:        https://example.com
 * License:           GPL v2 or later
 * Text Domain:       my-first-plugin
 * Domain Path:       /languages
 */

After saving the file, you can find this plugin on the “Plugins” page in the WordPress administration dashboard. You can click “Activate” to enable it. It doesn’t have any functionality yet, but you have successfully created a plugin that is recognized by WordPress.

Add a settings page for the plugin.

A common requirement is to add a backend administration page for a plugin. This can be achieved using the tools provided by WordPress. add_menu_page() Or add_options_page() It can be implemented using a function.

Recommended Reading The Ultimate Guide to WordPress Plugin Development: Building Professional Extensions from Scratch

We continue to add code to the main file to create a simple settings page.

// 钩子:在管理员菜单中添加一个新的页面
add_action('admin_menu', 'mfp_add_admin_menu');

function mfp_add_admin_menu() {
    add_options_page(
        '我的插件设置',          // 页面标题
        '我的插件',             // 菜单标题
        'manage_options',       // 所需权限
        'my-first-plugin',      // 菜单slug
        'mfp_settings_page_html' // 用于显示页面内容的回调函数
    );
}

// 设置页面的HTML内容
function mfp_settings_page_html() {
    // 检查用户权限
    if (!current_user_can('manage_options')) {
        return;
    }
    ?&gt;
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        <p>Welcome to the settings page for my first plugin!</p>
        <form action="/en/options.php/" method="post" data-trp-original-action="options.php">
            <?php
            // 输出设置字段(后续可在此添加)
            settings_fields('mfp_options_group');
            do_settings_sections('my-first-plugin');
            submit_button('保存设置');
            ?>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

This code uses add_action() The hook will call the function. mfp_add_admin_menu 挂载到 WordPress 的 admin_menu In terms of the implementation: When the administrator menu is created, our function is invoked, which adds a new sub-menu item to the “Settings” main menu. Clicking on this sub-menu item will then trigger the corresponding action. mfp_settings_page_html A function is used to render the page content.

Understanding WordPress Hooks and Filters

The core philosophy of WordPress is based on “hooks,” which allow you to insert custom code at specific points in the program’s execution flow. This enables you to modify or extend the core functionality of WordPress without having to directly alter the original source code. There are mainly two types of hooks: Actions and Filters.

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%

Using Action Hooks

Action hooks execute your code when specific events occur, such as posting an article, loading the administration backend, or generating the footer of a page. They do not expect a return value and are primarily used to perform a particular task. add_action() A function is used to attach a callback function to a specified action hook.

For example, we want to automatically add a copyright notice at the end of each article. This can be achieved by using… the_content This filter (which is also an action point) is used to achieve the desired functionality. However, in order to present the actions more purely and clearly, we choose to use… wp_footer The hook is used to display information at the bottom of the website’s front-end page.

add_action('wp_footer', 'mfp_add_footer_note');

function mfp_add_footer_note() {
    if (is_single()) { // 仅在文章页面显示
        echo '<p style="text-align:center; color:#666;">This article is presented to you by my plugin.</p>';
    }
}

Using Filter Hooks

Filter hooks are used to modify data before it is used or saved to a database. They expect you to receive a value, modify it, and then return the modified value. We use them… add_filter() A function is used to mount a callback function.

Recommended Reading Introduction to WordPress Plugin Development: Build Your Customized Functional Modules from Scratch

A classic example is modifying the length of an article’s summary. By default, WordPress sets the summary length to 55 words. We can change this setting by… excerpt_length Use filters to make changes to it.

add_filter('excerpt_length', 'mfp_custom_excerpt_length');

function mfp_custom_excerpt_length($length) {
    // 将摘要长度修改为 20 个单词
    return 20;
}

In this example, the function mfp_custom_excerpt_length The default length value has been received. $lengthThen, it returns our custom new length value of 20. WordPress will use this returned value to generate the summary.

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.

Plugin Security and Best Practices

Developing a popular plugin requires considering security, maintainability, and performance as essential factors. Following best practices can help avoid many common issues.

Data validation, escaping, and cleaning up

Never trust data entered by users or data retrieved from databases. Before processing any data, it must be validated, cleaned, and escaped.
* 验证(Validation):检查数据是否符合预期的格式或类型(如是否是邮箱、数字等)。可以使用 filter_var() Function or WordPress-related sanitize_*() Series of functions.
* 清理(Sanitization):清除数据中的非法或危险字符,使其变得安全。对于表单输入,常用 sanitize_text_field()
* 转义(Escaping):在将数据输出到 HTML、JavaScript 或 URL 时,根据上下文进行转义,以防止跨站脚本(XSS)攻击。WordPress 提供了丰富的转义函数,如 esc_html()esc_attr()esc_url() and wp_kses_post()

For example, to securely output a variable from a database:

// 假设 $user_input 是从数据库或表单获取的数据
echo '<div class="info">'`. esc_html($user_input)`.'</div>';
// 或者,如果允许一些安全的HTML标签
echo '<div class="info">'. wp_kses_post($user_input) . '</div>';

Plugin Internationalization and Localization

In order for your plugin to be used by users around the world, you need to add support for multiple languages. This process is known as internationalization (i18n). WordPress uses the GNU gettext framework to achieve this.

First of all, wrap all the strings that need to be translated using a specific function. The most commonly used one is… __()(Used for return values) and _e()(Used for direct output display.)

Modify the title of the management page we created earlier:

function mfp_settings_page_html() {
    if (!current_user_can('manage_options')) {
        return;
    }
    ?&gt;
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        <p><?php _e('欢迎来到我的第一个插件的设置页面!', 'my-first-plugin'); ?></p>
        ...
    </div>
    &lt;?php
}

Note that each translation function includes a text domain parameter (`‘my-first-plugin’`), which must match the one defined in the plugin header information. Text Domain Exactly the same. Then, you can use tools like Poedit to scan the translatable strings in the plugin code and generate the necessary translation files. .pot Template files, and create versions in different languages. .po and .mo Translate the file and place it in the plugin directory. /languages/ Inside the folder.

summarize

By following this guide, we have systematically covered the core steps of WordPress plugin development. From setting up a local development environment and creating a main file that includes standard header information, to utilizing action and filter hooks for in-depth interaction with the WordPress core, to the crucial aspects of security practices and internationalization preparation, you have now acquired the fundamental knowledge needed to build a plugin that is functional, secure, and reliable. Remember: excellent plugins are the result of clear code structure, rigorous security measures, and a thoughtful user experience. The best way to continue learning is to put these concepts into practice by starting with a simple plugin that solves a real-world problem, and then gradually exploring more complex APIs and features.

FAQ Frequently Asked Questions

What are the basic knowledge requirements for developing WordPress plugins?

You need to master the PHP programming language, as it is the core development language for WordPress. It is also essential to have a basic understanding of HTML, CSS, and JavaScript for handling front-end display and interactions. Familiarity with the basic concepts of MySQL databases (such as CRUD operations) is helpful, as WordPress uses MySQL to store data. Finally, it is crucial to understand the basic architecture and workflow of WordPress.

How to debug my WordPress plugin?

First, enable the WordPress debugging mode in the wp-config.php file by setting the appropriate option to `on`. define('WP_DEBUG', true); and define('WP_DEBUG_LOG', true); Set it to `true`. This will log error messages to the `/wp-content/debug.log` file, preventing them from being displayed directly to visitors. Secondly, by integrating professional debugging tools like Xdebug with your code editor (such as VS Code), you can use advanced features such as setting breakpoints and performing step-by-step debugging. Additionally, you can use the network and console panels in the browser’s developer tools to check AJAX requests and front-end JavaScript errors.

How can I submit the plugin I developed to the official WordPress plugin directory?

Before submitting your plugin, make sure it fully complies with WordPress’s official coding standards and best practices. Conduct a thorough code review and security check as well. You will need to register a WordPress.org account and then submit your plugin’s compressed package on the plugin submission page. The review team will examine your code to ensure its security, legality, and compliance with relevant guidelines. Once approved, your plugin will be added to the official WordPress repository, available for users around the world to download and install.

How can I add a setting option to my plugin in the WordPress Customizer?

The WordPress Customizer offers a way to configure settings in real-time. You can use it to… add_action('customize_register', 'your_function'); Hook: Used in callback functions. your_function In China, through $wp_customize The object includes a Section, a Setting, and a Control. This enables users to adjust options within the customizer interface and see the real-time effects on the front end, making it ideal for managing the visual settings of themes and plugins.