Basic Knowledge of WordPress Plugin Development
Before starting to write code, it is essential to understand the basic concepts of WordPress plugins. A WordPress plugin is essentially a collection of one or more PHP files that function through the various mechanisms provided by WordPress.APIandHookPlugins can be used to expand or modify the core functionality of WordPress. They can range from something as simple as adding a shortcut code to something as complex as building a complete e-commerce platform. All plugins are stored in a specific location within the WordPress software./wp-content/plugins/Under the directory, each plug-in has its own independent folder.
The core of developing plugins lies in understanding the workings of WordPress.动作钩子and过滤器钩子。动作钩子It allows you to execute custom PHP code at specific moments in time, such as when the page is loaded or when an article is published.过滤器钩子This allows you to modify various data generated by WordPress during its operation (such as article content, titles, and excerpts). Mastering the use of these hooks is key to plugin development.
In order for a plugin to be recognized by WordPress, each plugin must contain a standard plugin header comment. This comment block is usually located at the beginning of the plugin’s main PHP file and provides WordPress with basic information about the plugin, such as its name, description, version, and author. Without this header, the plugin will not appear in the list of plugins in the administration panel.
Recommended Reading In-Depth Understanding of WordPress Plugin Development: From Zero to Building Professional Extensions。
Create your first plugin
We will start by creating the simplest “Hello World” plugin. This plugin will display a custom welcome message at the top of the dashboard in the WordPress administration panel.
Initialize the plugin directory and the main file.
First of all, you need to set up your local development environment or a test site. /wp-content/plugins/ Create a new folder within the directory. Let’s name it… my-first-pluginThen, create a main PHP file inside that folder. We usually name it after the plugin; in this case, we will create it accordingly. my-first-plugin.php。
In my-first-plugin.php At the beginning of the file, the plugin header information must be added. This is the “identification card” of the plugin.
Write the plugin header information and core functions.
After the file is created, open it and enter the following code:
<?php
/**
* Plugin Name: 我的第一个插件
* Plugin URI: https://yourwebsite.com/my-first-plugin
* Description: 这是一个用于学习插件开发的入门示例,会在仪表盘显示欢迎信息。
* Version: 1.0.0
* Author: 你的名字
* Author URI: https://yourwebsite.com
* License: GPL v2 or later
* Text Domain: my-first-plugin
*/ This comment defines the basic information of the plugin. After saving the file, log in to your WordPress administration panel and go to the “Plugins” page. You should see a new plugin named “My First Plugin” there. Activate it now; it doesn’t have any functionality yet.
Recommended Reading WordPress Plugin Development Complete Guide: Building Your Own Plugin from Scratch。
Next, we will add the first feature to it. We will use… add_action() The function mounts a custom function to a WordPress action hook. Add the following code below the header comments:
\n// Add a welcome message at the top of the dashboard
function my_first_plugin_admin_notice() {
echo '<div class="notice notice-success is-dismissible"><p>Welcome to using “My First Plugin”! This is a great start.</p></div>'You have successfully installed the 'My First Plugin'!';
function my_first_plugin_admin_notice() {
echo 'This is my first plugin!';
}
add_action( 'admin_notices', 'my_first_plugin_admin_notice' ); Here, we have created something called… my_first_plugin_admin_notice The function’s purpose is to output a piece of HTML code that is used to display a notification in the WordPress backend style. Then, we use… add_action( ‘admin_notices’, ‘my_first_plugin_admin_notice’ ) \n Mount this function to admin_notices This action is hooked onto a specific hook. This means that whenever WordPress prepares to display management notifications in the background, our function will be executed.
After saving the file, refresh any page in the WordPress administration panel. You will see a green success message at the top of the page. Congratulations! Your first functional plugin has been successfully activated and is now working.
Add a settings page for the plugin.
A complete plugin usually needs to provide users with configuration options. We will add a simple settings page for “My First Plugin,” which will allow users to customize the text displayed in the welcome message.
Create a management menu item.
First of all, we need to add a menu item to the management sidebar in the WordPress backend. This can be done by using… add_action() The function is mounted. admin_menu Hook. Continue to add the following code to the main plugin file:
// 添加插件设置页面到后台菜单
function my_first_plugin_add_menu() {
add_menu_page(
‘我的第一个插件设置’, // 页面标题
‘第一个插件’, // 菜单标题
‘manage_options’, // 权限 (manage_options 表示管理员权限)
‘my-first-plugin-settings’, // 菜单 slug
‘my_first_plugin_settings_page’, // 用于显示页面内容的回调函数
‘dashicons-smiley’, // 菜单图标 (Dashicons)
100 // 菜单位置
);
}
add_action( ‘admin_menu’, ‘my_first_plugin_add_menu’ ); add_menu_page() The function is a core WordPress function used to add a top-level menu in the background. We defined the title of the page, the text to be displayed on the menu, and the access permissions (in this case, it is set to be accessible only to administrators). manage_optionsuniqueslug... as well as the names of the callback functions used to output the page content. my_first_plugin_settings_page。
Recommended Reading A Beginner's Guide to Cloud Hosting: A Step-by-Step Guide to Deploying and Managing Cloud Servers from Scratch。
Build a settings page form
Next, we need to define my_first_plugin_settings_page This function is used to render the HTML content of the settings page and handle the logic for saving the form data. It will create a simple form, and the data entered by users will be processed through WordPress. options The API is used for saving and reading data.
// 设置页面的内容
function my_first_plugin_settings_page() {
// 检查用户权限
if ( !current_user_can( ‘manage_options’ ) ) {
wp_die( __( ‘你没有权限访问此页面。’ ) );
}
// 保存表单数据
if ( isset( $_POST[‘my_first_plugin_message’] ) ) {
update_option( ‘my_first_plugin_custom_message’, sanitize_text_field( $_POST[‘my_first_plugin_message’] ) );
echo ‘<div class="“notice" notice-success is-dismissible”><p>Settings have been saved!</p></div>’;
}
// 获取已保存的消息
$saved_message = get_option( ‘my_first_plugin_custom_message’, ‘这是一个通过设置页面定制的欢迎消息!’ );
// 输出表单 HTML
?>
<div class="“wrap”">
<h1>My first plugin settings</h1>
<form method="“post”" action="/en/“”/" data-trp-original-action="“”">
<table class="“form-table”">
<tr>
<th scope="“row”"><label for="“custom_message”">Custom welcome message</label></th>
<td>
<input type="“text”" id="“custom_message”" name="“my_first_plugin_message”" value="”NO NUMERIC NOISE KEY" 1001” class="“regular-text”" />
<p class="“description”">Enter the text you want to display in the dashboard notifications.</p>
</td>
</tr>
</table>
<?php submit_button( ‘保存更改’ ); ?>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
<?php
} In this function, we first check the user's permissions. Then, we check whether a POST request has been submitted (i.e., whether the user has clicked the save button). If so, we use… update_option() The function saves the messages from the form to WordPress. options In the database table, and use it… sanitize_text_field() Perform security filtering. Then, we use… get_option() Read the previously saved value; if it doesn’t exist, use the default value. Finally, we output an HTML form that includes an input box.
Modify the notification function to use custom messages.
Finally, we need to modify the content that was created earlier. my_first_plugin_admin_notice The function should read the message from the options we have saved, instead of displaying fixed text.
\n// Modified notification function
function my_first_plugin_admin_notice() {
// Retrieve the custom message from the database
$custom_message = get_option( ‘my_first_plugin_custom_message’, ‘Welcome to “My First Plugin”! This is a successful start.’ );
echo ‘ \n// Modified notification function
function my_first_plugin_admin_notice() {
// Retrieve the custom message from the database
$custom_message = get_option( 'my_first_plugin_custom_message', 'Welcome to "My First Plugin"! This is a successful start.' );
echo '<div class="“notice" notice-success is-dismissible”><p>’ . esc_html( $custom_message ) . ‘</p></div>’;
} Now, activate the plugin, and you will see a “First Plugin” menu in the background sidebar. Click on it to modify the message and save it. Refresh other background pages, and you will notice that the notification message at the top has been replaced with the content you customized. At this point, a small plugin with basic create, read, update, and delete (CRUD) functions is complete.
Best Practices and Advanced Techniques for Plugin Development
Developing a maintainable, secure, and highly compatible plugin requires following certain best practices.
Ensure code security and data purification.
Security is the top priority in plugin development. Never trust data entered by users or data from external sources. WordPress provides a wealth of functions to help you clean, escape, and validate data.
* Purify input: Use functions such as sanitize_text_field()、sanitize_email()、sanitize_url() This is to process the data submitted from the form.
* Escape output: When outputting any data to HTML, JavaScript, or a URL, it must be escaped. Use < esc_html()、esc_attr()、esc_url() and wp_kses_post() Functions such as...
* Permission check: Before performing any management operations, it is essential to use the following command to check the permissions of the current user:
```bash
sudo -u admin check_permissions
``` current_user_can() Check whether the current user has the necessary permissions, for example… current_user_can( ‘manage_options’ )。
* Nonce verification: For operations involving data changes (such as form submissions and AJAX requests), use wp_nonce_field()、wp_verify_nonce() To prevent cross-site request forgery (CSRF) attacks, we can improve the form on the previous settings page by adding nonce validation to enhance security.
Implement the internationalization of the plug-in
In order for your plugin to be used by users around the world, internationalization is an essential step. This requires you to prepare translations for all the text strings that are displayed to users.
1. Use the text field: Define it in the plugin header comments. Text Domain(For example, my-first-plugin), and use it in all the strings that need to be translated. __(‘文本’, ‘my-first-plugin’) Or _e(‘文本’, ‘my-first-plugin’) Function wrapping.
2. Generate the translation file: Use tools such as Poedit to scan all translatable strings in the plugin and generate the file. .pot Template files, and then translate them into various languages. .po and .mo The document.
3. Loading the text field: During the plugin initialization process, use… load_plugin_textdomain() The function loads your translation files.
Managing the plugin lifecycle
A professional plugin should handle activation, deactivation, and uninstallation events properly. You can achieve this by creating the corresponding hook functions.
* Activate the hook: Use register_activation_hook() Register a function to be executed when the plugin is activated. This is commonly used for creating database tables, initializing default settings, or checking for environmental compatibility.
* Disable hooks: Use register_deactivation_hook()It is usually used to clean up temporary data or stop scheduled tasks.
* Uninstall hooks: Use the following command:
```shell
rm -rf /usr/local/lib/python3.8/site-packages/hook_example
``` register_uninstall_hook()Note: This hook is used to clean up all database options, custom tables, and files created by the plugin when the user completely deletes the plugin from WordPress. The operation should be carried out with caution, and users should be clearly informed about it.
summarize
This article takes you through the entire process of developing WordPress plugins from scratch. You first learned about the basic concepts of plugins, especially the key roles of action hooks and filter hooks. Then, you created your own plugin framework, which included a folder, a main file, and standard header information. add_action() Functions and admin_notices The hook has implemented the first display function. Next, by adding a settings page for the plugin, you learned how to use it. add_menu_page() Creating a backend menu, and how to use it update_option() and get_option() We performed operations such as adding, deleting, modifying, and querying data. Finally, we discussed best practices that must be followed in professional development, including secure coding, internationalization, and plugin lifecycle management. By following these steps and principles, you will have the ability to independently develop simple, useful, and secure WordPress plugins, and you can then build upon this foundation to explore more complex functionalities.
FAQ Frequently Asked Questions
What basic knowledge is required to develop WordPress plugins?
You need to master the basic syntax of the PHP language, as the plugin code is primarily written in PHP. Additionally, you should have a good understanding of HTML, CSS, and basic JavaScript for building the front-end interface and interactions. Most importantly, you need to be familiar with the core architecture of WordPress, especially its...HookSystems (actions and filters);选项API、数据库APIas well asREST APIIt is also crucial to understand WordPress’s coding standards and best practices for security.
How do I debug and test my plugin?
There are various methods for debugging WordPress plugin development. First of all, in your… wp-config.php The file is open in the program WP_DEBUG and WP_DEBUG_LOG This will log PHP errors and warnings to... /wp-content/debug.log In the file, it makes it easier to troubleshoot problems. Secondly, for code with complex logic, you can use… error_log() The function outputs the variable values to the log. It is also recommended to develop in a local environment (such as Local by Flywheel or XAMPP) or on a temporary test site to avoid impacting the production website. Using a version control system (such as Git) to manage code changes is a good practice as well.
How can my plugin be compatible with different versions of WordPress?
To ensure the wide compatibility of the plugin, the following points should be considered during development: Avoid using functions that are only introduced in the latest version of WordPress. If it is necessary to use such functions, make sure to provide appropriate documentation or alternatives for users of earlier versions of WordPress. function_exists() Perform conditional checks and provide fallback plans. Add these instructions in the comments at the beginning of the plugin. Requires at least and Tested up to Clearly state the range of WordPress versions your plugin supports. Regularly test your plugin on the latest version of WordPress and update your compatibility information in a timely manner. Following the official WordPress coding standards can also help minimize compatibility issues caused by core updates.
How do I distribute my plugin after it has been developed?
There are mainly two ways to distribute plugins. The first is to release them for free in the official WordPress plugin directory, which allows your plugin to be discovered and downloaded by millions of users around the world. You need to visit WordPress.org to submit your plugin and ensure that the code meets their guidelines and review standards. The second option is to sell the plugin as a commercial product through your own website. In this case, you are responsible for handling sales, payments, license verification, and customer support. For commercial plugins, OOP (Object-Oriented Programming) is often used to organize the code structure more effectively, and frameworks may be integrated to simplify license management, update notifications, and other functions. Regardless of the method chosen, it is crucial to provide clear documentation and timely support to users.
What's next, what's next?
Extended reading and practical knowledge
The following are related to the topic of this article and are suitable for further in-depth reading. Prioritize starting with the article that is closest to your current problem, and gradually expanding to surrounding topics usually works better.
- Top 10 WordPress Plugins Worth Installing in 2026 to Improve Website Performance and Security
- In-Depth Analysis of WooCommerce: Building a Powerful WordPress E-commerce Website from Scratch
- The 10 Most WorthInstalling WordPress Plugins in 2026 for Improving Website Performance and Security
- 10 Practical WordPress Plugins to Improve Website Performance and Security Significantly
- 10 Essential Plugins to Improve WordPress Website Performance and Security