From Beginner to Expert in WordPress Plugin Development: A Step-by-Step Guide to Creating Your First Custom Plugin

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

Why learn WordPress plugin development?

The reason WordPress has become the most popular content management system (CMS) in the world is largely due to its powerful scalability. At the heart of this scalability lies the use of plugins. By developing custom plugins, you can add any functionality you can imagine to your website without having to modify the core code of WordPress itself. This not only ensures the security of core updates but also makes your functionality modular, making it easy to manage and migrate.

Learning plugin development allows you to transition from being a WordPress “user” to a “creator.” Whether you’re creating unique features for clients, solving specific business needs, or packaging your ideas into products for sale in the market, mastering this skill opens up endless possibilities for you. More importantly, understanding the workflow of plugin development enables you to better debug and customize other plugins when you use them.

A standard WordPress plugin is structured as a folder that contains the main PHP file. This main file announces its presence to the WordPress system through specific comment headers. All the business logic—whether it’s adding a new widget, creating a custom post type, or processing form data—is implemented by using various “hooks” provided by WordPress.

Recommended Reading From Beginner to Expert: A Step-by-Step Guide to Developing Your Own Custom Features for WordPress Plugins

Building your first plugin project

Before you start developing, you need a local development environment. We recommend using tools such as XAMPP, MAMP, Local by Flywheel, or Docker to set up a local server with PHP, MySQL, and Apache/Nginx. Developing on your local WordPress installation will prevent any potential impact on your live website.

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

The basic file structure for creating a plugin

The simplest plugin can consist of just one file. In your WordPress installation directory, go to… wp-content/plugins Folder: Create a new folder, for example… my-first-pluginThen, create a main PHP file within this folder. The name of the file usually matches the name of the folder. my-first-plugin.php

Write the metadata header for the plugin.

In the main plugin file, the comment block at the top of the file is crucial. It tells WordPress the name, description, version, author, and other information about the plugin. A standard header looks like this:

<?php
/**
 * Plugin Name:       我的第一个插件
 * Plugin URI:        https://example.com/my-first-plugin
 * Description:       这是一个用于学习 WordPress 插件开发的自定义插件。
 * Version:           1.0.0
 * Author:            你的名字
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       my-first-plugin
 * Domain Path:       /languages
 */

After saving the file, log in to your WordPress administration panel and navigate to the “Plugins” page. You should see “My First Plugin” listed in the plugin directory; you can then activate it. At this point, a “blank” but functional plugin has been created. It doesn’t have any functionality yet, but its structure is correct.

Exploring the Core Mechanisms of WordPress: Hooks and Filters

The core of WordPress plugin development lies in understanding and utilizing its “hook” system. There are two types of hooks: action hooks and filter hooks. These are mechanisms that allow you to “insert” custom code or modify data at specific points in the WordPress workflow.

Recommended Reading An Introduction to WordPress Plugin Development: Building Your First Functional Extension from Scratch

Understanding how action hooks work

Action hooks allow you to execute your functions at specific moments in the WordPress execution process. For example, when the page has finished loading, or when an article is published. add_action() Functions can be used to mount your custom functions onto a hook. The basic syntax is:add_action( ‘hook_name’, ‘your_function_name’ );

Let's implement a feature: display a custom message at the bottom of the website's front-end pages. We will use the following approach: wp_footer This action hook.

function my_custom_footer_message() {
    echo '<p style="text-align: center; color: #666;">Thank you for visiting our website! This footer information was added using a custom plugin.</p>';
}
add_action( 'wp_footer’, 'my_custom_footer_message’ );

Add this code to your plugin’s main file. my-first-plugin.php Save the changes and refresh the website’s front-end page; you will see this line of text at the bottom of the page.

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%

Use filters to modify the default content.

Filter hooks are used to modify the data that is generated during the processing by WordPress. Unlike action hooks, filter functions must return a value. add_filter() A function is used to mount (apply) filters. For example, to modify the default content of an article title:

function modify_post_title( $title ) {
    if ( is_single() ) {
        return '【精选】’ . $title;
    }
    return $title;
}
add_filter( ‘the_title’, 'modify_post_title’ );

This function adds the “【Selected】” prefix before the title on single article pages, while the titles on other pages (such as the home page and list pages) remain unchanged. By combining actions and filters, you can control almost every aspect of WordPress.

Build a practical backend management page.

In order to allow plugin users to configure options, we usually need to create a backend administration page for them. This involves using the WordPress administration menu API.

Recommended Reading From Beginner to Expert: A Complete Guide to Developing WordPress Plugins and Building Highly Customizable Functional Modules

Add a new management menu item.

utilization add_menu_page() Or add_options_page() Functions such as these can be used to add a new page to the left sidebar menu in the WordPress administration panel. Let’s take the example of adding a page under the “Settings” submenu.

First, create a function to render the HTML content for the management page.

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 my_plugin_settings_page_html() {
    // 检查用户权限
    if ( ! current_user_can( ‘manage_options’ ) ) {
        return;
    }
    ?&gt;
    <div class="wrap">
        <h1></h1>
        <form action="/en/options.php/" method="post" data-trp-original-action="options.php">
            <?php
            // 输出设置字段和安全字段
            settings_fields( ‘my_plugin_settings’ );
            do_settings_sections( ‘my_plugin_settings’ );
            submit_button( ‘保存设置’ );
            ?>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

Registration settings, blocks, and fields

WordPress provides register_setting(), add_settings_section() and add_settings_field() This set of APIs is used to handle settings in a standardized manner. It automatically handles security verification (Nonce) as well as the saving and reading of options.

Next, we need a function to initialize these settings. This function should be mounted to… admin_init On the hook.

function my_plugin_settings_init() {
    // 注册一个新的设置选项组
    register_setting( ‘my_plugin_settings’, ‘my_plugin_options’ );

// 在页面中添加一个新的区块
    add_settings_section(
        ‘my_plugin_section_1’,
        ‘基础设置’,
        null, // 回调函数,用于输出区块描述,可为空
        ‘my_plugin_settings’
    );

// 在区块内添加一个字段
    add_settings_field(
        ‘my_plugin_field_text’,
        ‘欢迎语’,
        ‘my_plugin_field_text_cb’,
        ‘my_plugin_settings’,
        ‘my_plugin_section_1’,
        [
            ‘label_for’ =&gt; ‘my_plugin_field_text’,
            ‘class’ =&gt; ‘my_plugin_row’,
        ]
    );
}
add_action( ‘admin_init’, ‘my_plugin_settings_init’ );

// 字段的回调函数,用于输出字段的 HTML
function my_plugin_field_text_cb( $args ) {
    $options = get_option( ‘my_plugin_options’ );
    ?&gt;
    <input type="text" id="<?php echo esc_attr( $args[‘label_for’] ); ?>"
           name="my_plugin_options[<?php echo esc_attr( $args[‘label_for’] ); ?>]"
           value="<?php echo esc_attr( $options[ $args[‘label_for’] ] ?? ‘’ ); ?>">
    <p class="“description”">This text will be displayed on the website’s home page.</p>
    &lt;?php
}

Add the page link to the menu.

Finally, use… add_options_page() Add the page we created to the “Settings” menu.

function my_plugin_add_settings_page() {
    add_options_page(
        ‘我的插件设置’, // 页面标题
        ‘我的插件’, // 菜单标题
        ‘manage_options’, // 所需能力
        ‘my-plugin-settings’, // 菜单别名
        ‘my_plugin_settings_page_html’ // 渲染页面的回调函数
    );
}
add_action( ‘admin_menu’, ‘my_plugin_add_settings_page’ );

Now, after activating the plugin, you can find the “My Plugins” option under the “Settings” menu in the WordPress admin panel. Click on it to access a settings page that contains a text field where you can enter and save a welcome message. Afterwards, you can… get_option( ‘my_plugin_options’ ) Retrieve and use this value from the front end.

Implementing the front-end functionality of the plugin and considering security aspects

When implementing front-end functionality in plugins, security is the top priority. Never trust the data provided by users; it must be validated, cleaned, and escaped accordingly.

Assume we want to use the “welcome message” that has been saved in the backend settings and display it at the top of the website’s homepage. First, we need to retrieve this option from the database, and then display it securely.

function display_frontend_greeting() {
    // 1. 获取数据
    $options = get_option( ‘my_plugin_options’ );
    $greeting = $options[‘my_plugin_field_text’] ?? ‘’;

// 2. 如果内容为空,则不输出任何东西
    if ( empty( $greeting ) ) {
        return;
    }

// 3. 在输出前进行清理和转义
    $safe_greeting = esc_html( $greeting );

// 4. 输出到前端(这里假设只在首页显示)
    if ( is_front_page() ) {
        echo ‘<div class="“my-plugin-greeting”"><p>’. $safe_greeting . ‘</p></div>’;
    }
}
add_action( ‘wp_body_open’, ‘display_frontend_greeting’ );

Here, we have used… esc_html() We have a function that escapes HTML characters to prevent cross-site scripting attacks (XSS). We also check whether the data is empty and use conditional tags accordingly. is_front_page() To control the position of the output, you need to mount the function to the appropriate location. wp_body_open Hooks can ensure that the content is displayed immediately after the start of the body tag on the page.

In addition, internationalization is also an important practice in plugin development. By using… __() and _e() By using translation functions and correctly setting the plugin’s Text Domain, your plugin can be translated into any language. In the plugin’s header metadata mentioned earlier, we have already defined the necessary settings. Text Domain: my-first-pluginIn the code, it should be used like this:

echo esc_html__( ‘Hello, World!’, ‘my-first-plugin’ );

summarize

Through the practical examples in this article, we have completed a complete but simple process for developing a WordPress plugin. We started by creating the basic file structure and metadata for the plugin, and then gradually delved into the core mechanisms of WordPress—the hook system. We used actions and filters to control the program flow and modify data. Next, we built a backend administration page with custom fields, allowing users to configure the plugin’s settings, and finally, we ensured that these settings were securely displayed on the website’s front end.

This process covers several key aspects of plugin development: file organization, the use of hooks, the creation of backend interfaces, option management, and the secure handling of front-end data. Remember that a good plugin should not only be powerful in functionality but also secure, efficient, and easy to maintain. Next, you can try adding more features to your plugin, such as custom post types, shortcodes, utilities, or REST API endpoints, to further deepen your understanding of WordPress plugin development.

FAQ Frequently Asked Questions

Can a plugin contain only one PHP file?

Yes, the simplest WordPress plugin can consist of just one PHP file, as long as that file contains the correct plugin header comments. However, for plugins with more complex functionality, it is recommended to organize the code into separate files. For example, you can store the backend logic, the frontend functionality, and the common functions in different files. This will improve the readability and maintainability of the code.

How to debug a plugin you developed yourself?

It is recommended to enable the debugging mode in WordPress. This can be done by locating the `wp-config.php` file in the root directory of your website. wp-config.php In the document, it will be stated that... WP_DEBUG The constant is set to trueIn this way, PHP errors, warnings, and notifications will all be displayed. Additionally, these can be used in combination with other tools or methods as well. error_log() The function writes debugging information to the server’s error log, or uses the console in the browser’s developer tools for JavaScript debugging.

What are the security guidelines that must be followed when developing plugins?

The primary principle is: Never trust any user input. Always be cautious of all data that comes from users. $_GET$_POST$_COOKIE The data obtained needs to be validated and cleaned before it is output in HTML. esc_html()esc_attr()esc_url() Escape functions such as `%s` and `%1$s` when constructing database queries. It is essential to use them to prevent errors or security vulnerabilities. $wpdb->prepare() Methods to prevent SQL injection attacks. In addition, check the permissions of the current user (for example…). current_user_can()This is also an essential step.

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

First of all, make sure that your plugin fully complies with WordPress’s coding standards and the GPL license. You need to visit WordPress.org, create an account, and then submit your plugin’s compressed package on the plugin submission page. The official team will conduct a manual review to check the quality of the code, its security features, the documentation, and its compliance with WordPress’s requirements. Once the review is successful, your plugin will be added to the official WordPress repository, receive automatic update support, and become available for users around the world to search for and install.