A Complete Guide to WordPress Plugin Development: Building Your First Plugin from Scratch

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

Preparing the WordPress Plugin Development Environment

Before starting to write code, it is essential to establish a stable and efficient local development environment. This not only allows you to conduct tests securely but also simulates the actual server configuration. For WordPress plugin development, we strongly recommend using local server software such as XAMPP, MAMP, or Local by Flywheel. These tools can easily set up an environment on your computer that includes Apache, PHP, and MySQL.

Next, you will need a code editor. Visual Studio Code, PhpStorm, or Sublime Text are all excellent choices; they offer syntax highlighting, code suggestions, and debugging features, which can greatly improve your development efficiency. After installing and configuring these tools, download the latest version of the WordPress core files and install them on your local server.

In addition, it is recommended to initialize a version control system, such as Git, in the root directory of your plugin project.git initThe command creates a new repository, which helps you track code changes, revert errors, and facilitate future team collaboration. Additionally, consider enabling the debugging mode in WordPress.wp-config.phpThe document willWP_DEBUGThe constant is set totrueThis will display PHP errors and warnings during the development process, helping you to quickly locate issues.

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

Create the basic structure for your first plugin.

A standard WordPress plugin has a specific directory and file structure. First, navigate to the WordPress installation directory.wp-content/pluginsFolder: Create a new folder for the plugin you are about to develop. The name should be short, unique, and describe the functionality of the plugin. For example:my-first-plugin

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

Writing the main file of a plugin

Within this folder, create a file named….phpFiles with a specific extension are used as the main files for plugins and usually have the same name as the folder they are part of. For example…my-first-plugin.phpThis file serves as the entry point for the plugin, and the plugin header comments at the top are essential. They provide WordPress with metadata about the plugin.

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

In this comment section,Plugin NameThis is the only required field; the additional information will help users identify your plugin in the backend. Once you complete this step, you have actually created a plugin that can be activated. Log in to the WordPress backend and navigate to the “Plugins” menu. You should see “My First Plugin” there, although it currently doesn’t have any functionality.

Building plugin functionality and class encapsulation

For the clarity and maintainability of the code, it is recommended to organize the code using an object-oriented approach. In the main file, or in a separate file, define a class that encapsulates all the functionality of the plugin.

if ( ! class_exists( 'My_First_Plugin' ) ) {
    class My_First_Plugin {
        public function __construct() {
            // 构造函数,用于初始化动作和过滤器
            add_action( 'init', array( $this, 'init' ) );
        }

public function init() {
            // 插件初始化时执行的操作
            // 例如:注册短代码、自定义文章类型等
        }
    }

// 实例化插件类
    new My_First_Plugin();
}

This structure organizes your functions within an independent namespace, which prevents conflicts with function names from other plugins or themes.

Recommended Reading WordPress Plugin Development: Building Custom Functional Modules from Scratch

Implement the core functions: actions and filters.

The power of WordPress plugins lies in their Hook system, which includes Actions and Filters. Understanding and utilizing these components is essential for effective plugin development.

Use action hooks to add functionality.

Action hooks allow you to insert your own code at specific points during the WordPress execution process. For example, if you want to automatically add a piece of text after the article content, you can use them for that purpose.the_contentThe filter is a special type of “action.” More typical actions include…wp_footerThis is used to add content at the bottom of the page.

public function __construct() {
    add_action( 'wp_footer', array( $this, 'add_custom_footer_text' ) );
}

public function add_custom_footer_text() {
    echo '<p style="text-align: center;">Thank you for reading! This content was generated by my first plugin.</p>';
}

In this example,add_custom_footer_textThe method will be called at the bottom of each page to display a custom piece of text.

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 filter hooks to modify data

Filter hooks are used to modify data before it is sent to the database or the browser. A common example is modifying the title of an article. We can use them to…the_titleFilters.

public function __construct() {
    add_filter( 'the_title', array( $this, 'customize_title' ) );
}

public function customize_title( $title ) {
    // 只在主循环中且不是后台管理界面时修改
    if ( ! is_admin() && in_the_loop() ) {
        return '📖 ' . $title;
    }
    return $title;
}

This filter function takes the original title as a parameter and returns the modified title. The logic involved is to add a book emoji before the article title that is displayed on the front end.

Plugin Internationalization and Configurable Options

To make the plugin available to users around the world, internationalization (i18n) is an essential step. Additionally, providing users with a backend settings page to configure the plugin’s behavior can greatly enhance the professionalism of the plugin.

Recommended Reading WordPress Plugin Development Beginner’s Guide: Building Your First Functional Plugin from Scratch

Implement text translation support.

WordPress uses the GNU gettext technology for internationalization. You need to wrap all the strings that are displayed to users, either in the frontend or backend of the plugin, with specific functions.

First of all, in the plugin header of the main file, we have already defined…Text DomainandDomain PathNext, load the text field within the initialization function.

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.
public function init() {
    load_plugin_textdomain(
        'my-first-plugin',
        false,
        dirname( plugin_basename( __FILE__ ) ) . '/languages/'
    );
}

Then, in the code, use the translation function wherever the text needs to be displayed. For example, in the previous footer text:

\necho '<p style="text-align: center;">' . esc_html__( '感谢阅读!本内容由我的第一个插件生成。', 'my-first-plugin' ) . '</p>';

esc_html__()The function translates the text and performs HTML escaping to ensure security. Translators can use it..poand.moYou need to provide files to create different language versions for your plugin.

Create a background settings page.

Using the WordPress Settings API allows you to create a standard and secure settings page for your plugin. This typically involves several steps: registering the settings, adding settings areas and fields, and creating the menu page.

public function __construct() {
    add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
    add_action( 'admin_init', array( $this, 'settings_init' ) );
}

public function add_admin_menu() {
    add_options_page(
        '我的第一个插件设置', // 页面标题
        '我的插件', // 菜单标题
        'manage_options', // 权限
        'my-first-plugin', // 菜单slug
        array( $this, 'settings_page_html' ) // 回调函数,用于输出页面HTML
    );
}

public function settings_init() {
    register_setting( 'my_first_plugin_settings', 'my_first_plugin_options' ); // 注册一组设置

add_settings_section(
        'my_first_plugin_section',
        __( '基本设置', 'my-first-plugin' ),
        null,
        'my-first-plugin'
    );

add_settings_field(
        'footer_text',
        __( '自定义页脚文本', 'my-first-plugin' ),
        array( $this, 'footer_text_field_html' ),
        'my-first-plugin',
        'my_first_plugin_section'
    );
}

public function footer_text_field_html() {
    $options = get_option( 'my_first_plugin_options' );
    ?&gt;
    <input type='text' name='my_first_plugin_options[footer_text]' value='<?php echo esc_attr( $options['footer_text'] ?? '' ); ?>'>
    <?php
}

public function settings_page_html() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    ?>
    <div class="wrap">
        <h1></h1>
        <form action="/en/options.php/" method="post" data-trp-original-action="options.php">
            <p><strong>Output:</strong>  
  
</p>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

Now, users can configure the footer text on the “Settings” -> “My Plugins” page.add_custom_footer_textThe method can be modified to retrieve values from this option, making the plugin configurable.

summarize

Through this guide, we have gone through the main steps of WordPress plugin development: from setting up a local environment and creating a basic file structure to organizing code using object-oriented methods. We delved into WordPress’s core extension mechanisms—action and filter hooks—and implemented practical functions for adding content to the footer and modifying article titles. Finally, we improved the professionalism and usability of the plugin by enabling internationalization to cater to users around the world, as well as by using the Settings API to create a secure backend configuration interface. Plugin development is a continuous process of learning and optimization. Once you have mastered these basic concepts, you can further explore more advanced topics such as customizing article types, AJAX interactions, and REST API integration, in order to build powerful and well-written WordPress plugins.

FAQ Frequently Asked Questions

Does developing plugins necessarily require the use of object-oriented programming?

It’s not mandatory, but highly recommended. Although procedural programming (using a series of functions) can quickly implement functionality, as the number of plugin features increases, the code becomes difficult to manage and maintain, and there’s a higher risk of function name conflicts with other plugins. Object-oriented programming encapsulates code within classes, making it easier to organize and extend the system over time.$thisVariables and namespaces (in newer versions of PHP) help to organize code more effectively, and represent industry best practices for building medium to large-scale plugins.

How to safely handle user input or data from a database?

Whenever you need to display a variable on a page, you must escape it accordingly. WordPress provides a series of helper functions for this purpose. The appropriate function should be used depending on the context: whether you are displaying the variable inside an HTML tag or within an attribute.esc_html()Oresc_attr()Output it in a JavaScript variable, using the following code: ```javascript let name = "Jack"; console.log(name); ```wp_json_encode()Oresc_js(); Output in the URL, usingesc_url()Never trust user input or unprocessed data; escaping data is crucial for preventing Cross-Site Scripting (XSS) attacks.

What conditions must be met for a plugin to be submitted to the official WordPress directory?

Plugins submitted to the WordPress.org plugin directory must comply with a series of strict guidelines. These include: the plugin code must be compatible with the GPL license; it cannot contain any paywalls, encrypted or obfuscated code; it must include full internationalization support; it needs to follow WordPress's coding standards and documentation norms; and it cannot engage in malicious activities such as phone number attribution or cryptocurrency mining. Additionally, your plugin's main file must contain standard plugin header information, and you need to provide a complete readme file.readme.txtThe document.

How should I debug my plugin code?

First of all, make sure that it has been enabled in the development environment.WP_DEBUGFor more complex debugging tasks, you can use…error_log()The function records the information in the server’s error log, or uses it for other purposes.var_dump()andwp_die()To check the value of a variable (this is only for use in the development environment), a more efficient method is to use the Xdebug tool in an integrated development environment (such as PhpStorm) for step-by-step debugging. Additionally, for WordPress…WP_DEBUG_LOGandWP_DEBUG_DISPLAYConstants can be used to control whether errors should be logged to a file or displayed on the screen.