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

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

Why is it necessary to develop custom plugins?

In the WordPress ecosystem, plugins are the core of extending website functionality. Although there are thousands of ready-made plugins available, developing custom plugins offers unique advantages. When your needs are very specific, or when the combination of existing plugins is too cumbersome and inefficient, a custom-made plugin is the best solution. Custom plugins can perfectly match your business logic, avoiding potential conflicts that may arise from using multiple plugins, and they usually perform better than general-purpose plugins that perform multiple functions. More importantly, by developing them yourself, you have full control over the quality and security of the code.

From a learning perspective, understanding the plugin development mechanism is an essential step towards gaining a thorough grasp of WordPress. It enables you to transition from being a “user” to a “creator,” allowing you to more flexibly meet various customization needs and even lays a solid foundation for future product development or career advancement.

Preparatory work: Setting up the development environment

Before starting to write code, a stable and isolated development environment is crucial. This not only protects your production website but also allows you to test and debug freely.

Configuring the local development environment

It is recommended to use local server software packages such as Local by Flywheel, XAMPP, or MAMP. These tools simulate a web server environment (Apache/Nginx, MySQL, PHP) on your computer, allowing you to develop your website offline. Once the installation is complete, create a new WordPress site as your “sandbox” (a testing environment for new projects or changes).

Code Editor Selection

A powerful code editor can significantly improve development efficiency. Visual Studio Code is a very popular choice nowadays; it is lightweight, free, and comes with a rich set of extensions, such as syntax highlighting, code suggestions, and debugging tools specifically for PHP and WordPress. PHPStorm is another powerful Integrated Development Environment (IDE) that offers more advanced features for code analysis and refactoring.

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 Basic File Structure

The simplest WordPress plugin can simply consist of a single main PHP file. However, well-structured plugins typically have a clear organization of files and directories. This is especially true for the files located within your local WordPress installation directory. wp-content/plugins Inside the folder, create a new folder for your plugin, for example: my-first-pluginThis folder will contain all the files for the plugin.

Build your first plugin, “Hello Admin”.”

We will create a plugin called “Hello Admin” whose functionality is very simple: it displays a custom welcome message at the top of the dashboard in the WordPress administration panel. This example covers the core elements of plugin development: the main file, hooks, and basic functions.

Create the main plug-in file

In your plugin folder… my-first-plugin Inside, create a file named… my-first-plugin.php This is the plugin’s entry file. Open it and, first of all, add the standard plugin information comments at the beginning of the file. These comments are necessary for WordPress to recognize the plugin.

<?php
/**
 * Plugin Name:       Hello Admin
 * Plugin URI:        https://yourwebsite.com/hello-admin
 * Description:       一个简单的插件,用于在管理后台显示欢迎信息。
 * Version:           1.0.0
 * Author:            你的名字
 * License:           GPL v2 or later
 * Text Domain:       hello-admin
 */

Use hooks to add functionality.

The core mechanism of WordPress is known as “Hooks,” which allow you to insert your own code at specific points in the program’s execution. There are mainly two types of Hooks: Action Hooks and Filter Hooks. To display content in the administration panel, we need to use Action Hooks.

When WordPress loads the header of the administration backend, it provides a component or element with the name… admin_notices Action hooks. We can use them to... add_action() The function mounts our custom function to this hook.

Add the following code below the comments in the main file:

// 钩子函数:在管理后台显示通知
function hello_admin_display_message() {
    // 确保只对管理员显示,使用 current_user_can() 检查权限
    if ( current_user_can( 'manage_options' ) ) {
        echo '<div class="notice notice-success is-dismissible"><p>Welcome back, administrator! This is your custom “Hello Admin” plugin in action.</p></div>';
    }
}
// 将我们的函数挂载到 ‘admin_notices’ 这个动作钩子上
add_action( 'admin_notices', 'hello_admin_display_message' );

Testing and Activation

Save the file. Now, log in to the administration panel of your local WordPress website (which is usually located at …). /wp-adminNavigate to the “Plugins” menu, and you should see “Hello Admin” in the list of plugins. Click “Enable”. After enabling it, refresh the dashboard page. You will see a green success message at the top of the page, displaying the welcome message you defined. This indicates that your first plugin has been successfully activated and is now working!

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%

Add configurable options for the plugin.

A plugin that only displays fixed information has limited usefulness. Next, we need to make it configurable, allowing administrators to customize the messages to be displayed through a settings page. This involves creating a management menu page, processing form data, and using the options API to store the data.

Create a management menu page.

We need to add a settings page in the administration backend. This can be achieved by... add_menu_page() Or add_submenu_page() Function implementation: We continue to add code to the main plugin file.

First, create a function to generate the HTML content for the settings page, and register a menu item:

// 创建插件设置页面
function hello_admin_add_settings_page() {
    add_options_page(
        'Hello Admin 设置', // 页面标题
        'Hello Admin',      // 菜单标题
        'manage_options',   // 所需权限
        'hello-admin',      // 菜单slug
        'hello_admin_render_settings_page' // 用于渲染页面的回调函数
    );
}
add_action( 'admin_menu', 'hello_admin_add_settings_page' );
// 渲染设置页面的HTML
function hello_admin_render_settings_page() {
    ?&gt;
    <div class="wrap">
        <h1>Hello Admin settings</h1>
        <form method="post" action="/en/options.php/" data-trp-original-action="options.php">
            <?php
            settings_fields( 'hello_admin_settings_group' ); // 设置组名称
            do_settings_sections( 'hello-admin' ); // 页面slug
            submit_button(); // 提交按钮
            ?>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

Registration settings, fields, and data storage

Next, we need to use WordPress’s Settings API to securely register, validate, and save our options. Create another function and… admin_init Run it on the hook.

// 初始化设置
function hello_admin_settings_init() {
    // 注册一个设置,将其存储在 wp_options 表中
    register_setting( 'hello_admin_settings_group', 'hello_admin_custom_message', 'sanitize_text_field' );
// 在页面上添加一个设置区域(可以省略,此处为清晰而加)
    add_settings_section(
        'hello_admin_section',
        '自定义消息设置',
        null, // 可选的区域描述回调函数
        'hello-admin'
    );
// 在区域中添加一个字段
    add_settings_field(
        'hello_admin_message_field',
        '欢迎消息',
        'hello_admin_message_field_callback',
        'hello-admin',
        'hello_admin_section'
    );
}
add_action( 'admin_init', 'hello_admin_settings_init' );
// 渲染消息输入字段
function hello_admin_message_field_callback() {
    $message = get_option( 'hello_admin_custom_message', '欢迎回来,管理员!' ); // 获取已保存的值,没有则用默认值
    echo '<input type="text" name="hello_admin_custom_message" value="' . esc_attr( $message ) . '" class="regular-text" />'echo '<p class="description">Please enter the welcome message you would like to display in the administration panel here.</p>';
}

Modify the display function to use the configuration items.

Finally, we need to modify the initial notification display function. hello_admin_display_message()Let it come from the database options. hello_admin_custom_message The content is read from a file, rather than being hardcoded.

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.
function hello_admin_display_message() {
    if ( current_user_can( 'manage_options' ) ) {
        $custom_message = get_option( 'hello_admin_custom_message', '欢迎回来,管理员!' ); // 获取自定义消息
        if ( ! empty( $custom_message ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $custom_message ) . '</p></div>';
        }
    }
}

Now, save all the changes. Return to the WordPress backend, and you will see “Hello Admin” under the “Settings” menu. Go to that page, modify the message, and save it. Refresh the dashboard, and you will notice that the message displayed has been changed to the content you just set. At this point, a custom plugin with basic configuration functions has been created.

Best Practices for Plugin Development and Next Steps

After implementing the basic functions, following best practices will make your plugin more professional, secure, and easier to maintain.

Security comes first: Always validate, escape, and clean user input. Use the functions provided by WordPress for this purpose. esc_html(), esc_attr(), sanitize_text_field(), wp_nonce_field() Never trust data directly from users or databases.

Code Organization and Comments: As the functionality of your plugin grows, break down the code into separate classes or files. Using object-oriented programming (OOP) can improve the reusability and organization of your code. Add clear comments to your functions and classes; this is crucial for both you in the future and for potential collaborators.

Internationalization Preparation: If you plan to release your plugin publicly, it should support internationalization (i18n). This means that you need to… __() Or _e() Functions such as these wrap all the user-facing strings and set the appropriate text domain. This allows others to translate your plugin into other languages.

Performance considerations: Load your plugin resources (CSS, JavaScript) only when necessary. Use conditional statements wisely to avoid loading scripts that are required only in certain pages. Optimize database queries and make proper use of WordPress’s Transients API for caching.

In-Depth Exploration: After mastering the basics, you can explore more advanced topics such as creating custom post types (CPTs) and custom taxonomies, adding shortcodes, developing custom widgets, integrating REST APIs, or creating a drag-and-drop block for your plugin.

summarize

By following this guide, you have completed the entire process of building a fully functional WordPress custom plugin from scratch. You have learned the basic concepts of plugin development, including the file structure, the core Hook system, and how to use the Settings API to create secure configuration pages. Although the “Hello Admin” plugin is simple, it demonstrates the core patterns of plugin development: declaring the plugin, hooking its functions into the WordPress framework, processing data, and displaying the results. With these fundamentals in hand, you now have the key to exploring WordPress’s extensive extension capabilities. Remember, continuous learning, adhering to best practices, and being willing to put them into practice are the essential steps to improving your plugin development skills.

FAQ Frequently Asked Questions

How many files does a WordPress plugin require at a minimum?

The simplest plugin can consist of just a single main PHP file. As long as this file contains the correct plugin header comments, WordPress will be able to recognize and activate it. However, as the functionality of the plugin becomes more complex, it is common to split the code into multiple files for better organization. This may include separate JavaScript and CSS files, or PHP class files that are organized by functional modules.

What is the difference between the action hook `add_action` and the filter hook `add_filter`?

Action Hooks are used to execute a piece of code or a specific function at a certain moment. They are not designed to return any value; their sole purpose is to “perform an action.” For example, sending an email after an article is published.

Filter Hooks are used to modify data. They accept an input value and are expected to return a modified value. For example, before the article title is displayed in the browser, its content can be modified. The key difference lies in the following: Actions are executed, while Filters modify the data and then return the modified result.

How to securely save user input to a database?

Be sure to use the option API functions provided by WordPress.update_option()andregister_setting()register_setting()The function allows you to specify a cleanup callback function (for example)...sanitize_text_fieldThe data is automatically processed before being saved. Never use it directly.$wpdbOr using SQL statements to insert unprocessed user data can lead to serious security vulnerabilities (such as SQL injection).

How to avoid conflicts with other plugins when developing a new one?

Good coding practices are the key to avoiding conflicts. Add unique prefixes to all your functions, classes, variables, and option names. For example, use…hello_admin_display_messagerather than the common onedisplay_messageEncapsulate your CSS styles and JavaScript code within specific class or ID selectors. When adding hooks, make sure that your callback functions only execute under the conditions you need them to (for example, by checking the current page or the user’s permissions).