WordPress, as the world's most popular content management system, owes its strong scalability largely to plugins. By developing plugins, you can add any custom functionality to your website without having to modify the core code. This guide will take you through the entire process of creating your first functional plugin, covering every key step from preparing your development environment, writing the code, to testing and releasing it.
Preparatory work and environment setup
Before you write the first line of code, you need a suitable development environment. This not only improves efficiency but also helps to avoid the risks associated with debugging on a live website.
Setting up a local development environment
It is recommended to use local server software packages such as XAMPP, MAMP, or Laragon. These packages allow you to install Apache, MySQL, and PHP with just one click, perfectly simulating a live production environment. Make sure that your PHP version is compatible with the version of WordPress you plan to use; the WordPress official website usually provides the latest version requirements.
Recommended Reading WordPress Plugin Development Complete Guide: Creating Your First Functional Plugin from Scratch。
Installing WordPress and a code editor
Install a brand-new WordPress site on your local server for plugin development and testing. Additionally, choose a powerful code editor, such as Visual Studio Code or PhpStorm. These editors offer excellent support for PHP syntax highlighting, code suggestions, and debugging, which can significantly enhance your coding experience.
Create your first plug-in file
The most basic WordPress plugin can consist of just one file. We will start with a simple “Hello World” plugin to understand the structure of plugins.
The structure of the main file of the plug-in
First of all, in WordPress… wp-content/plugins Inside the directory, create a new folder, for example… my-first-pluginWithin this folder, create the main plugin file, which is usually named after the plugin itself, for example: my-first-plugin.php。
Each plugin must contain specific plugin information comments at the beginning of the file; this is crucial for WordPress to recognize the plugin. Here is a basic example:
<?php
/**
* Plugin Name: 我的第一个插件
* Plugin URI: https://example.com/my-first-plugin
* Description: 这是一个用于学习的简单功能插件。
* Version: 1.0.0
* Author: 你的名字
* License: GPL v2 or later
* Text Domain: my-first-plugin
*/ After saving the file, go to the “Plugins” page in the WordPress administration panel. There, you will see this plugin and be able to activate it. Although it doesn’t have any functionality yet, you have successfully created a compliant plugin framework.
Recommended Reading Step-by-Step Guide to Mastering WordPress Plugin Development from Scratch。
Add basic functionality to the plugin.
After activating the plugin, let’s add a simple feature to it: a line of custom text to be displayed at the bottom of the website page. We will use WordPress’s built-in functionality for this. wp_footer Hooks.
Below the plugin information comments, add the following code:
\n// Output custom text in the footer of the website
function myfp_add_footer_text() {
echo '<p style="text-align: center;">Thank you for using my first plugin!</p>';
}
add_action( 'wp_footer', 'myfp_add_footer_text' ); Save the file and refresh the website’s front end; you will see this centered text at the bottom of the page. This example demonstrates how to use it. add_action() The function “mounts” your custom function to the core execution points of WordPress.
Implement a practical management feature.
A complete plugin usually needs to provide a configuration interface in the WordPress administration panel. Next, we will add a simple settings page to the plugin that allows administrators to customize the text displayed at the bottom of the page.
Create a management menu page.
We need to add a sub-menu page under the “Settings” menu in the backend. This will require the use of… add_options_page() Function.
First, create a function to render the HTML content for the settings page, and then mount it to the appropriate location. admin_menu On the hook.
Recommended Reading Starting from scratch: Why choose WordPress plugin development?。
// 添加插件设置页面到后台菜单
function myfp_add_admin_menu() {
add_options_page(
'我的插件设置', // 页面标题
'我的插件', // 菜单标题
'manage_options', // 权限(管理员)
'my-first-plugin', // 菜单slug
'myfp_settings_page' // 用于输出页面内容的回调函数
);
}
add_action( 'admin_menu', 'myfp_add_admin_menu' );
// 设置页面的HTML内容
function myfp_settings_page() {
?>
<div class="wrap">
<h1>My first plugin settings</h1>
<form method="post" action="/en/options.php/" data-trp-original-action="options.php">
<?php
settings_fields( 'myfp_settings_group' ); // 设置字段组
do_settings_sections( 'my-first-plugin' ); // 设置区域
submit_button(); // 提交按钮
?>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
<?php
} Registration settings, fields, and data storage
Having just the page is not enough; we need to use the WordPress API to securely register, validate, and save the options. This involves three core functions:register_setting(), add_settings_section() and add_settings_field()。
// 初始化插件设置
function myfp_settings_init() {
// 注册一个新的设置项到数据库的 `wp_options` 表
register_setting( 'myfp_settings_group', 'myfp_footer_text' );
// 在设置页面添加一个区域
add_settings_section(
'myfp_section',
'页脚文字设置',
null, // 区域描述回调函数,这里不需要
'my-first-plugin'
);
// 在刚添加的区域里创建一个字段
add_settings_field(
'myfp_field_footer',
'显示的文本',
'myfp_field_footer_cb', // 用于输出字段HTML的回调函数
'my-first-plugin',
'myfp_section'
);
}
add_action( 'admin_init', 'myfp_settings_init' );
// 渲染文本输入字段的回调函数
function myfp_field_footer_cb() {
$text = get_option( 'myfp_footer_text', '感谢使用我的第一个插件!' ); // 获取已保存的值
echo '<input type="text" name="myfp_footer_text" value="' . esc_attr( $text ) . '" class="regular-text">'echo '<p class="description">The text entered here will be displayed at the bottom of the website page.</p>';
} The update feature now uses the saved settings.
Finally, let’s modify what we wrote earlier. myfp_add_footer_text The function is designed to read the values set by the administrator from the database.
function myfp_add_footer_text() {
$footer_text = get_option( 'myfp_footer_text', '感谢使用我的第一个插件!' );
if ( ! empty( $footer_text ) ) {
echo '<p style="text-align: center;">'`. esc_html($footer_text)`.'</p>';
}
}
add_action( 'wp_footer', 'myfp_add_footer_text' ); Now, log in to the WordPress admin dashboard, go to “Settings” -> “My Plugins”, and you can modify the footer text before saving it. Refresh the website’s front end to see the customized content in effect.
Plugin Security, Optimization, and Preparation for Release
A qualified plugin must take into account the best practices for security, performance, and internationalization.
Implement data validation and escaping
Never trust data that comes from user input or is directly retrieved from a database. In the example above, we… esc_attr() Escape attributes in input fields by using… esc_html() Escape the output on the front end. For more complex scenarios, it is advisable to use… sanitize_text_field() Use this to clean the input data. wp_kses_post() This allows for the safe output of HTML content.
Add internationalization support.
In order for the plugin to be used by users around the world, it is necessary to prepare translations for all the strings that are displayed to the users. This requires the use of… __() and _e() Define functions such as `wait()`, and declare a text field.
Update the comments at the top of the plugin to ensure that… Text Domain Consistent with subsequent calls. Then modify the strings in the code, for example:
// 在设置字段描述中使用国际化函数
echo '<p class="description">' . esc_html__( '这里输入的文字将显示在网站页脚。', 'my-first-plugin' ) . '</p>';
// 在输出函数中使用
$default_text = __( '感谢使用我的第一个插件!', 'my-first-plugin' );
$footer_text = get_option( 'myfp_footer_text', $default_text ); After that, you can use tools like Poedit to create the necessary files. .pot Template files for translators to create .po and .mo Translate the document.
Perform final testing and packaging.
Before releasing the plugin, it is necessary to test its functionality in various environments (such as different PHP versions and different WordPress versions). Make sure that operations such as activating, deactivating, saving settings, and deleting data do not cause errors or leave behind redundant data. You can write an uninstallation and cleanup function to handle these tasks properly. register_uninstall_hook() Option to clean the database when a user deletes a plugin.
Finally, compress your plugin folder into a zip file. .zip The file: This compressed package can be installed directly using the “Upload Plugin” feature in the WordPress backend, and it also meets the format requirements for submission to the official WordPress plugin directory.
summarize
By following this guide, you have completed the entire process of building a fully functional WordPress plugin from scratch. You have learned how to create the basic files for a plugin, use action hooks to add functionality, utilize the WordPress Settings API to build a backend administration interface, and understood key concepts such as security, internationalization, and packaging. Although this simple footer text plugin is basic, the plugin structure, hook mechanism, and Settings API it uses are the foundation for developing any more complex plugins. Next, you can explore more advanced features such as shortcodes, custom post types, and REST API endpoints to gradually improve your plugin development skills.
FAQ Frequently Asked Questions
Is it necessary to master PHP in order to develop WordPress plugins?
Yes, PHP is the core programming language used for developing WordPress and its plugins. You need to master the basic syntax of PHP, as well as concepts related to functions, arrays, and object-oriented programming. Knowledge of HTML, CSS, and basic JavaScript is also essential for creating plugins that include user interfaces.
Can the name of the main plugin file be chosen arbitrarily?
Sure, but it must match the name of the main PHP file inside the plugin folder. For clarity, the main file is usually named the same as the plugin folder or has a similar name. index.phpMost importantly, the file header must contain the correct plugin information comment block. WordPress identifies plugins by parsing this comment block.
Why don’t the changes I made to my plugin settings take effect after I save them?
Please follow these steps to troubleshoot the issue: First, make sure that your setting fields have been validated and approved. register_setting() Correct registration, and... settings_fields() The name of the setting group in the function call matches the one used in the function. Secondly, check the form… action Does the attribute point to something? options.phpFinally, when outputting the content on the front end, make sure you are using the correct methods or technologies. get_option() The function is called, and the option names passed in are exactly the same as those used during registration.
How can I make my plugin clean up data when it is disabled?
You can use register_uninstall_hook() This function is used to register an uninstall hook. Within the callback function of this hook, you can use… delete_option() This function is used to delete all database options created by the plugin. Please note that this action is irreversible and should only be performed when the user explicitly chooses to “delete” the plugin, rather than just “disable” it.
Can free plugins be submitted to the official WordPress directory?
Yes, WordPress officially encourages developers to submit free plugins that meet the required standards to its plugin directory. To do this, you need to have a WordPress.org account and carefully read the plugin submission guidelines. Your code must adhere to certain coding standards and must not contain any malicious code or violate the terms of the license. Once your plugin is successfully submitted, users will be able to search for and install it directly from the WordPress administration panel.
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.
- How to choose and customize the perfect WordPress theme for you
- WordPress Plugin Development Guide: Creating Your First Custom Plugin from Scratch
- Becoming a WordPress Plugin Developer: A Complete Guide from Scratch
- From Zero to One: A Comprehensive Guide and Practical Tips for Building Professional Websites with WordPress
- WordPress Plugin Development Complete Guide: From Beginner to Expert – Creating Professional Extensions