WordPress is the most popular content management system (CMS) in the world, and its strong scalability is largely due to its plugin architecture. When you find that the existing features do not meet your needs, developing your own plugin becomes the best option. This not only solves specific problems but also provides an excellent opportunity to gain a deep understanding of the core workings of WordPress. This guide will take you through the entire process of developing your first WordPress plugin, from setting up the environment, to writing the code, to finally releasing it.
Preparation of the development environment and tools
Before you start writing code, you need a suitable development environment. This will ensure that your development process is efficient and in line with WordPress's best practices.
Setting up a local development environment
The preferred option is to set up a local server environment on your own computer. You can use tools such as XAMPP, MAMP (for Mac), WAMP (for Windows), or the more flexible Docker. These toolkits integrate an Apache server, a MySQL database, and PHP, perfectly simulating the conditions required for WordPress to run online. After installing the local server, download the latest version of WordPress from the official WordPress.org website and follow the standard “5-minute installation” guide to configure it locally.
Recommended Reading A Beginner's Guide to WordPress Plugin Development: Building Your First Functional Plugin from Scratch。
Code editors and essential tools
A powerful code editor is essential. Tools like Visual Studio Code, PhpStorm, or Sublime Text are all excellent choices, as they offer syntax highlighting, intelligent code suggestions, and debugging features. In addition, you will also need a version control system, such as Git, to manage your code changes. Although the first plugin (for version control) may seem simple, developing the habit of using version control is crucial for future development.
Create your first plug-in file
Every WordPress plugin begins with a main file, which contains the header comments necessary for WordPress to recognize the plugin.
The main file structure of the plugin
In your local WordPress installation directory, navigate towp-content/pluginsFolder: Create a new folder here and name it…my-first-plugin(The name should be concise and describe the plugin’s functionality.) Within this folder, create a PHP file that usually has the same name as the folder:my-first-plugin.phpThis file will serve as the entry point for the plugin.
Write the header information for the plug-in
At the beginning of this main file, you must add a plugin header comment that complies with WordPress standards. This comment provides basic information about the plugin. Here is a basic example:
<?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
*/ This code is the “identity card” of the plugin.Plugin NameThis is a required field; it determines the name of the plugin that will be displayed in the WordPress administration panel. It is also recommended to fill in other information such as the description and version number. After saving the file, go to the “Plugins” page in the WordPress administration area. You should see “My First Plugin” listed in the plugin directory, and you will be able to activate it. Currently, this plugin does not have any functionality yet.
Recommended Reading WordPress Plugin Development Complete Guide: Creating Your First Functional Plugin from Scratch。
Add basic functions to the plug-in
After the plugin is activated, we will add two of its most basic features: the ability to insert custom text at the end of an article’s content, and a simple management page for managing the plugin settings.
Using hooks to modify article content
The core mechanism of WordPress is the “Hook” system, which allows you to insert your own code at specific points in the program’s execution. Action Hooks are used to perform certain actions, while Filter Hooks are used to modify data. We need to add a line of text at the end of an article’s content, and this can be achieved by using the Hook system.the_contentThis filter hook.
Below the comments at the top of your main plugin file, add the following function and hook:
// 在文章内容末尾添加自定义文本
function myfp_add_footer_text( $content ) {
// 仅在主循环的单篇文章页面添加
if ( is_single() && in_the_loop() && is_main_query() ) {
$custom_text = '<p><em>Thank you for reading! This article was generated by “My First Plugin”.</em></p>';
$content .= $custom_text;
}
return $content;
}
// 将函数挂载到 ‘the_content’ 过滤器上
add_filter( 'the_content', 'myfp_add_footer_text' ); After saving the file, refresh the article page on the website’s front end, and you will see the added text at the bottom of the article content. In this code segment…myfp_add_footer_textThe function receives the original data.$contentAfter checking the page conditions, custom HTML paragraph text was added to the resulting content, and the modified content was then returned.add_filter()The function then associates our custom function with the core filters of WordPress.
Create a simple management menu.
Next, we need to create a settings page for the plugin in the WordPress administration area. This involves using action hooks to add a new item to the management menu. Add the following code:
// 在后台管理菜单中添加一个新页面
function myfp_add_admin_menu() {
add_menu_page(
'我的第一个插件设置', // 页面标题
'我的插件', // 菜单标题
'manage_options', // 所需权限
'my-first-plugin', // 菜单slug
'myfp_admin_page_html', // 用于输出页面内容的回调函数
'dashicons-admin-generic', // 图标(可选)
100 // 菜单位置
);
}
add_action( 'admin_menu', 'myfp_add_admin_menu' );
// 定义管理页面的HTML内容
function myfp_admin_page_html() {
// 检查用户权限
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<div class="wrap">
<h1></h1>
<p>Welcome to the settings page for “My First Plugin.” This is the beginning of your journey with developing plugins for websites.</p>
</div>
<?php
} Save and refresh the WordPress backend. You should see a new “My Plugins” menu item near the bottom of the left sidebar. Click on it to enter a simple settings page. Here,add_menu_page()The function is responsible for registering the top-level menu page.myfp_admin_page_html()The function is responsible for rendering the HTML content of that page.
Plugin Security and Code Optimization
When developing plugins, security and maintainability should be key considerations from the very beginning.
Recommended Reading Starting from scratch: Why choose WordPress plugin development?。
Data Validation and Escaping
Never trust user input or external data. Any data that is to be displayed to the browser or saved in a database must be processed before being used. WordPress provides a wealth of helper functions to assist with this. For example, when outputting variables to HTML attributes, it is recommended to use appropriate validation and sanitization methods to ensure the data is safe and reliable.esc_attr()When outputting to HTML text, useesc_html()When outputting to a URL, useesc_url()In the previous…myfp_admin_page_html()In the function, we used…esc_html()Output the page title securely.
Use classes to organize the code
As the number of plugin functions increases, placing all functions in the global namespace can easily lead to conflicts and confusion. It is a good practice to use PHP classes to encapsulate the functionality of plugins. This improves the organization, readability, and reusability of the code. Below is a basic framework for rewriting our previous functions using classes:
class My_First_Plugin {
// 构造方法,用于初始化钩子
public function __construct() {
add_filter( 'the_content', array( $this, 'add_footer_text' ) );
add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
}
public function add_footer_text( $content ) {
// ... 函数实现同上 ...
}
public function add_admin_menu() {
// ... 函数实现同上 ...
}
public function admin_page_html() {
// ... 函数实现同上 ...
}
}
// 实例化插件类
new My_First_Plugin(); This approach binds all related methods and properties together in a single object, resulting in a clearer structure.
summarize
By following this guide, you have completed the essential steps to create a WordPress plugin from scratch: setting up the environment, creating the plugin file with standard header information, using action hooks and filter hooks to add functionality to article content, and creating a management interface. You have also gained a basic understanding of the importance of security and code organization. This is just the beginning; the world of WordPress plugin development is vast. You can explore more advanced features such as Shortcodes, Widgets, Custom Post Types, and REST API endpoints. Remember that reading the core code, referring to the implementation of excellent plugins, and consulting the official developer documentation are the best ways to continuously improve your skills.
FAQ Frequently Asked Questions
What technologies are essential for developing plugins?
Developing WordPress plugins requires a solid understanding of the basics of PHP, HTML, CSS, and JavaScript. PHP is the core language, as WordPress itself is written in PHP, and you will use it to write the logic for your plugins. HTML/CSS are used to build the user interface, while JavaScript (especially jQuery and modern ES6+ versions) can be used to enhance interactivity and make AJAX requests. Having a basic understanding of MySQL is also helpful for handling data.
Why isn’t my plugin displayed in the background (i.e., in the administration area of the website)?
Please first check the following points: 1. Whether the main plugin file has been placed in the correct location.wp-content/pluginsInside the independent folders within the directory. 2. The plugin header comments in the main file (especially…)Plugin Name:1. Check whether the file format is correct and error-free.
2. Check whether the file encoding is UTF-8 without a BOM.
3. Check whether there are any syntax errors that cause PHP parsing failure. You can check the WordPress debug log for this (which requires enabling the debug mode in the WordPress settings).wp-config.phpEnable in...WP_DEBUG)。
How to test a plugin without affecting the online website?
It is highly recommended to develop and test plugins in a local development environment (such as Local by Flywheel or XAMPP) or on a separate test server (Staging Site). Never test unverified new plugins directly on a production website that is currently in use and contains important data. Use version control tools (such as Git) to manage your code, so that you can easily revert to previous versions in case of any issues.
How should plugins be updated to new versions?
You should update the comment at the top of the plugin's main file.Version:For larger updates, it is recommended to follow semantic versioning (SemVer). For example, add a revision number (e.g., 1.0.1) to fix bugs, a minor version number (e.g., 1.1.0) for backward-compatible new features, and a major version number (e.g., 2.0.0) for incompatible updates. You can also implement an update detection mechanism (e.g., by hosting plugin information on your own server or in the WordPress plugin directory) to notify users of updates in the background.
What are the requirements for releasing a plugin to the official directory?
If you want to submit a plugin to the official WordPress.org plugin directory, you need to meet the following main requirements: The plugin code must be compatible with the GPLv2 or later license; the code quality must be satisfactory and meet the “WordPress Coding Standards”; the plugin’s functionality should be general and practical, rather than being customized for a specific website; the plugin must not contain any malicious code or spam links. Before submitting, be sure to carefully read the detailed submission guidelines and requirements in the “Developer Center” of the official directory.
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.
- What is WordPress? A comprehensive introduction to a content management system
- Preface: Why choose WordPress for development?
- How to choose and customize the perfect WordPress theme for you
- From Beginner to Expert: A Complete Guide to Building a Professional Website with WordPress
- WordPress Website Building 101: A Comprehensive Guide to Creating Professional Websites from Scratch