A Beginner's Guide to WordPress Plugin Development: Building Your First Custom Plugin from Scratch

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

Preparing the WordPress Plugin Development Environment

Before you start writing code, you need a suitable development environment. This not only improves your development efficiency but also helps you debug and test your plugins more effectively. First of all, you need to set up a WordPress runtime environment on your local computer. You can choose to use integrated development environments such as XAMPP, MAMP, or Local by Flywheel, which can quickly install PHP, MySQL, and Apache/Nginx servers. For the WordPress core files, it is recommended to download and install the latest stable version from the official website.

Make sure your PHP version meets the minimum requirements for WordPress, and enable the error reporting feature; this is crucial for debugging. You can do this by…wp-config.phpAdd the following code to the file to enable debug mode:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true); // 将错误记录到 /wp-content/debug.log
define('WP_DEBUG_DISPLAY', false); // 不在页面上显示错误

In addition, a powerful code editor is essential, such as Visual Studio Code, PhpStorm, or Sublime Text. These editors typically offer syntax highlighting, code suggestions, and integration with version control systems, which can significantly improve the coding experience. Finally, it is recommended to install developer tools in your browser and consider using browser extensions specifically designed for WordPress, to make it easier to check hooks, query the database, and monitor website performance.

Recommended Reading WordPress Plugin Development Beginner's Guide: Creating Your First Functional Module from Scratch

Create your first plug-in file

The most basic form of a WordPress plugin is a PHP file. All plugins are stored in a specific directory within WordPress’s file structure./wp-content/plugins/Within the directory, each plugin can be either an independent PHP file or a folder that contains multiple files.

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

First, create a folder with a unique name for your plugin, for example:my-first-pluginInside this folder, create the main plugin file, which is usually named the same as the folder itself.my-first-plugin.phpThe beginning of this file must contain a plugin header comment that complies with WordPress standards. This comment provides the WordPress system with basic information about the plugin.

Example of a header comment in the main plugin file:

<?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
 */

The “Plugin Name” in this comment is a required field; it determines the name of the plugin that will be displayed in the backend administration interface. Additional information such as the version number and the author helps users understand the plugin. After creating this file, please place it in the appropriate location./wp-content/plugins/my-first-plugin/Table of Contents. At this point, log in to your WordPress administration panel and go to the “Plugins” page. You should see a new plugin named “My First Customized Plugin,” and you can activate it. Although it doesn’t do anything yet, you have successfully created the basic framework for a plugin.

Handling the activation and deactivation of plugins

Plugins often need to perform initialization and cleanup tasks when they are activated or deactivated, such as creating database tables, setting default options, or removing temporary data. WordPress manages these processes through two special hooks:register_activation_hookandregister_deactivation_hook

Recommended Reading From Absolute Beginner to Expert: A Comprehensive Guide to WordPress Plugin Development and Best Practices

You can define these hooks in the main plugin file. For example, when the plugin is activated, we might want to write a default configuration option to the database; when the plugin is deactivated, we might need to remove that option. The implementation code is as follows:

// 定义插件激活时执行的函数
function my_plugin_activate() {
    // 添加一个默认选项到数据库
    add_option('my_plugin_default_option', '这是默认值');
    // 或者可以在这里初始化自定义数据库表(需要更复杂的SQL)
}
register_activation_hook(__FILE__, 'my_plugin_activate');

// 定义插件停用时执行的函数
function my_plugin_deactivate() {
    // 删除之前创建的选项
    delete_option('my_plugin_default_option');
    // 注意:通常不在停用钩子中删除数据,以免用户重新激活时丢失设置
    // 更常见的清理工作在卸载钩子中处理
}
register_deactivation_hook(__FILE__, 'my_plugin_deactivate');

It should be noted that…register_deactivation_hookIt is usually used for lightweight cleaning tasks, while permanent data deletion (such as removing database tables) should be handled within the uninstallation hooks. The uninstallation functionality must be implemented accordingly.register_uninstall_hookRegister now. Using these hooks properly will ensure that your plugin behaves in a standard manner and will not leave any redundant data on the website.

Understanding and using hooks and filters

The core of WordPress plugin development lies in the “Hook” mechanism, which allows you to insert custom code at specific points in the program’s execution flow to modify or extend the core functionality of WordPress. 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%

Action hooks allow you to execute custom functions when specific events occur. For example, when an article is published…publish_post), when loading the content at the top of the web pagewp_head) or during initialization in the administration backendadmin_initYou can use it.add_action()A function is used to mount your code. Here’s a simple example that automatically adds a custom piece of text at the end of each article:

function add_custom_footer_to_content($content) {
    if (is_single()) { // 仅在单篇文章页面添加
        $custom_text = '<p><em>Thank you for reading this article!</em></p>';
        $content .= $custom_text;
    }
    return $content;
}
// 使用‘the_content’过滤器,注意这是一个过滤器(Filter)的例子
add_filter('the_content', 'add_custom_footer_to_content');

As shown in the code above, we are actually using a filter. The filter hook is used to modify the data that is passed to it. The key difference between a filter and an action is that a filter must return the modified value. Typical examples of filters include…the_content(Modify the content of the article)the_title(Changed the title) Andexcerpt_length(Changed the length of the abstract.) Correspondingly,add_filter()The function is used to mount a filter function.

Creating custom hooks for others to extend

A well-designed plugin not only utilizes the core WordPress hooks but also provides its own custom hooks, allowing other developers to extend the functionality of your plugin.do_action()A function can create an action hook for use.apply_filters()It is possible to create a filter hook.

Recommended Reading WordPress Plugin Development Complete Guide: Building Your Own Plugin from Scratch

For example, before your plugin processes certain data, you could provide a filter that allows others to modify the input parameters.

// 定义插件的主要处理函数
function my_plugin_process_data($input_data) {
    // 在核心处理前,允许其他开发者通过过滤器修改 $input_data
    $filtered_data = apply_filters('my_plugin_filter_input', $input_data);

// ... 使用 $filtered_data 进行核心处理 ...

// 在处理完成后,触发一个动作钩子,通知其他开发者
    do_action('my_plugin_after_processing', $filtered_data);

return $result;
}

By creating custom hooks, your plugin becomes highly extensible and adheres to the development philosophy of WordPress itself.

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.

Add a management page and settings options for the plugin.

Most useful plugins require a backend administration interface that allows website administrators to configure the plugin options. WordPress provides a rich API for creating administration menus and setup pages.

First of all, you need to useadd_action('admin_menu', 'your_function')Use a hook to register a menu item. In the corresponding function, apply it accordingly.add_menu_page()Oradd_submenu_page()A function is used to add a top-level menu or submenus. Below is a basic example for adding a top-level menu and setting up the corresponding page:

// 钩入 admin_menu 来添加管理菜单
function my_plugin_add_admin_menu() {
    add_menu_page(
        '我的插件设置',           // 页面标题
        '我的插件',               // 菜单标题
        'manage_options',         // 权限(管理员)
        'my-plugin-settings',     // 菜单slug
        'my_plugin_settings_page', // 用于显示页面内容的回调函数
        'dashicons-admin-generic', // 图标(Dashicon)
        80                         // 菜单位置
    );
}
add_action('admin_menu', 'my_plugin_add_admin_menu');

// 定义设置页面的显示内容
function my_plugin_settings_page() {
    // 检查用户权限
    if (!current_user_can('manage_options')) {
        return;
    }
    ?&gt;
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        <form action="/en/options.php/" method="post" data-trp-original-action="options.php">
            <?php
            // 输出设置字段和非ce字段
            settings_fields('my_plugin_options_group');
            do_settings_sections('my-plugin-settings');
            submit_button('保存设置');
            ?>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

Registration and verification settings fields

Just having a page is not enough; you need to use the WordPress Settings API to securely register, store, and validate the settings options. This process involves using…register_setting()add_settings_section()andadd_settings_field()Functions such as...

The following code demonstrates how to register a set of setting options and a text field:

// 初始化插件设置
function my_plugin_settings_init() {
    // 注册一个设置选项组及其数据
    register_setting(
        'my_plugin_options_group', // 选项组名,需与settings_fields()参数一致
        'my_plugin_settings',      // 存储在wp_options表中的选项名
        'my_plugin_sanitize_input' // 可选的验证回调函数
    );

// 添加一个设置区域
    add_settings_section(
        'my_plugin_section_main',
        '主要设置',
        null, // 区域描述的回调函数,可为空
        'my-plugin-settings' // 所属页面的slug
    );

// 向该区域添加一个具体的字段
    add_settings_field(
        'my_plugin_field_text',
        '示例文本字段',
        'my_plugin_field_text_render', // 渲染字段HTML的回调函数
        'my-plugin-settings',
        'my_plugin_section_main'
    );
}
add_action('admin_init', 'my_plugin_settings_init');

// 渲染文本输入字段的函数
function my_plugin_field_text_render() {
    $options = get_option('my_plugin_settings');
    $value = $options['text_field'] ?? ''; // PHP 7.0+ 空合并运算符
    ?>
    <input type='text' name='my_plugin_settings[text_field]' value='<?php echo esc_attr($value); ?>'>
    <?php
}

// 清理和验证输入的函数
function my_plugin_sanitize_input($input) {
    $sanitized_input = [];
    if (isset($input['text_field'])) {
        // 清理文本输入,移除非法标签
        $sanitized_input['text_field'] = sanitize_text_field($input['text_field']);
    }
    return $sanitized_input;
}

Through the Settings API, WordPress automatically handles the saving of options, security verification, and permission checks, which greatly simplifies the development process and enhances security.

summarize

Through this guide, we have systematically gone through the main steps of WordPress plugin development: from setting up the environment and creating the basic plugin files, to understanding and utilizing the core hook system, and finally adding a professional management interface and settings options to the plugin. Each step has highlighted key code snippets and standard practices. The essence of plugin development lies in making effective use of WordPress’s extensive hook system to extend its functionality, while adhering to its API specifications to ensure security and compatibility. Remember that starting with a simple idea, gradually adding more features, and conducting thorough testing throughout the development process is an effective approach to creating high-quality plugins. Next, you can explore more advanced topics, such as creating custom post types, adding shortcodes, handling AJAX requests, and internationalizing your plugin.

FAQ Frequently Asked Questions

To develop a WordPress plugin, do I need to be proficient in PHP?

Yes, a solid foundation in PHP is essential. This is because both the WordPress core and its plugins are written in PHP. You need to understand PHP syntax, functions, and concepts such as object-oriented programming. Additionally, having a basic knowledge of HTML, CSS, and JavaScript is very helpful for creating user interfaces and implementing interactions.

How many files must a plugin contain?

There is no mandatory requirement. A plugin can contain only one PHP main file. However, as the functionality becomes more complex, it is advisable to modularize the code across multiple files.admin.phpHandle the backend tasks.public.phpHandle the front-end.includesIt is a better practice to store common functions in a folder, as this helps with the organization and maintenance of the code.

Why does my plugin cause the website to go blank (show a white screen) after it is activated?

This is usually caused by a fatal error, such as a syntax error, or attempting to call a function or class that does not exist. Please make sure that you have…wp-config.phpIt has been enabled.WP_DEBUGPattern, and check it.wp-content/debug.logError message from the file: You can quickly restore website access by disabling your plugin via FTP or a file manager (by renaming the plugin folder).

How to securely handle data submitted by users from the front end?

You must never trust data entered by users. Before processing any data from forms, URL parameters, or cookies, it must be validated, cleaned, and escaped. WordPress provides a large number of security functions to help with this, such as…sanitize_text_field()(Clean the text)esc_url()(Escaped URLs)wp_kses_post()(Filter the content using the allowed HTML tags) andintval()(Convert to an integer.) When outputting the data to an HTML page, be sure to use…esc_html()esc_attr()Escape the following functions.

How can I make the text in my plugin support multiple languages?

This needs to be achieved through internationalization (i18n). In your code, replace all strings that need to be translated with appropriate placeholders or functions for generating localized versions.__()Or_e()Function wrapping. Then, set the necessary parameters correctly in the comments at the beginning of the plugin.Text DomainandDomain PathUse tools like Poedit to create it..potTemplate files, and generate versions of these files in different languages..poand.moWordPress will automatically load the corresponding translations based on the language settings of the website.