Why learn WordPress plugin development?
WordPress, as the world's most popular content management system, owes its strong scalability in large part to the vast number of plugins available. Learning how to develop plugins not only allows you to customize functionality according to your own needs but also helps you gain a deeper understanding of WordPress's core architecture, thereby improving your technical skills. Furthermore, it enables you to turn your creative ideas into viable products that can be published online. By developing your own plugins, you have full control over the quality of the code, ensuring the security of your website, and avoiding potential compatibility issues that may arise from using third-party plugins.
A basic WordPress plugin is essentially one or more PHP files located in a specific directory. It interacts with the core WordPress system through the rich API provided by WordPress, such as action hooks, filter hooks, shortcodes, and widgets. Understanding this mechanism is a prerequisite for successfully developing any plugin.
Preparing the development environment and infrastructure
Before writing the first line of code, it is essential to establish a good development environment. You will need a local server environment (such as XAMPP, Local by Flywheel, or DevKinsta), a code editor (such as VS Code or PhpStorm), and a WordPress installation for testing purposes.
Recommended Reading The Ultimate Guide to WordPress Plugin Development: Mastering Core Principles and Practical Projects。
The entry point for the plugin is a main PHP file. The comments at the beginning of this file are crucial for WordPress to recognize the plugin. Let’s start by creating the basic structure of the plugin.
Create the main file for the plugin.
The main file of a plugin is usually named after the plugin itself. For example, if we create a plugin called “My First Plugin,” its main file can be named…my-first-plugin.phpThis file must be placed in…/wp-content/plugins/my-first-plugin/Under the directory.
The file header must contain standard plugin information comments. 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
* Domain Path: /languages
*/ After saving this file, go to the “Plugins” page in the WordPress administration dashboard. You should see the new plugin listed there, and you will be able to activate it. It doesn’t have any functionality yet, but the basic framework has been established.
Establishing the basic directory structure for a plugin
A plugin with a clear structure is conducive to long-term maintenance. It is recommended to create the following directories:
* /assets/Used to store static resources such as CSS, JavaScript, and images.
* /includes/This directory is used to store the core PHP class files and function files.
* /languages/Used to store internationalization translation files (.po/.mo).
Recommended Reading The Essence of Tailwind CSS: Unveiling the Working Principles of this Practical, Atomic CSS Framework。
main filemy-first-plugin.phpIt should only be responsible for the initialization of the plugin, such as defining constants, importing other files, and registering hooks.
Implement the core functionality: creating management menus and pages.
A common plugin feature is to add a management menu page in the WordPress backend. We will achieve this using WordPress’s “Menu Page API”.
Add a top-level menu in the backend.
We need to useadd_menu_page()Function. This function is usually used in...admin_menuThis action hook is called when it is triggered. We add the following code to the main file:
// 定义在管理员菜单初始化时执行的功能
function mfp_add_admin_menu() {
add_menu_page(
'我的插件设置', // 页面标题
'我的插件', // 菜单标题
'manage_options', // 所需权限
'my-first-plugin', // 菜单slug
'mfp_display_settings_page', // 用于显示页面内容的回调函数
'dashicons-admin-generic', // 菜单图标(Dashicon)
6 // 菜单位置
);
}
// 将函数挂载到 `admin_menu` 钩子上
add_action('admin_menu', 'mfp_add_admin_menu'); Create the display content for the settings page.
In the code above,mfp_display_settings_pageThis is a callback function responsible for generating the HTML content for the settings page. We need to define this function:
// 设置页面的显示内容
function mfp_display_settings_page() {
// 检查用户权限
if (!current_user_can('manage_options')) {
wp_die(__('你没有权限访问此页面。'));
}
?>
<div class="wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<form action="/en/options.php/" method="post" data-trp-original-action="options.php">
<?php
// 输出设置字段和安全nonce字段
settings_fields('mfp_options_group'); // 设置组的名称
do_settings_sections('my-first-plugin'); // 页面slug
submit_button('保存设置');
?>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
<?php
} This code creates a standard WordPress settings page framework, which utilizes the following components internally:settings_fields()anddo_settings_sections()This means that we will use the WordPress Settings API to manage our options, which is the safest and most standardized approach.
Use the Settings API to manage plugin options.
Handle it directly.$_POSTThe data poses security risks. The WordPress Settings API handles data validation, security, and storage for us, making it the preferred method for managing plugin settings.
Recommended Reading The Ultimate WooCommerce Plugin Guide: Building a Professional Cross-Border E-commerce Website from Scratch。
Registration settings, fields, and chapters
We need toadmin_initInitialize our settings within the hook. First, use…register_setting()Register a setting option.
function mfp_register_settings() {
// 注册一个设置:`mfp_options` 是存储在`wp_options`表中的键名
register_setting(
'mfp_options_group', // 设置组名,需与`settings_fields()`参数一致
'mfp_options', // 选项名
'mfp_sanitize_options' // 可选:数据清洗回调函数
);
// 添加一个设置章节
add_settings_section(
'mfp_main_section', // 章节ID
'主要设置', // 章节标题
'mfp_main_section_callback', // 章节介绍的回调函数
'my-first-plugin' // 所属页面slug
);
// 在章节中添加一个文本字段
add_settings_field(
'mfp_text_field', // 字段ID
'示例文本', // 字段标签
'mfp_text_field_callback', // 用于渲染字段HTML的回调函数
'my-first-plugin', // 所属页面slug
'mfp_main_section' // 所属章节ID
);
}
add_action('admin_init', 'mfp_register_settings'); Define the rendering and cleaning functions for the fields.
Now, we need to define the various callback functions that were used above, which are responsible for generating the HTML for the output fields and cleaning the data.
// 主章节的描述文本
function mfp_main_section_callback() {
echo '<p>This is the main settings area for the plugin.</p>';
}
// 文本字段的HTML输出
function mfp_text_field_callback() {
// 从数据库获取现有值
$options = get_option('mfp_options');
$value = $options['mfp_text_field'] ?? ''; // PHP 7.0+ 空合并运算符
echo '<input type="text" name="mfp_options[mfp_text_field]" value="' . esc_attr($value) . '" class="regular-text">';
}
// 数据清洗函数(可选但推荐)
function mfp_sanitize_options($input) {
$sanitized_input = [];
if (isset($input['mfp_text_field'])) {
// 对文本字段进行基本的清洗,如去除标签
$sanitized_input['mfp_text_field'] = sanitize_text_field($input['mfp_text_field']);
}
return $sanitized_input;
} At this point, a complete plugin with a security settings page has been created. Once the plugin is activated, you can find the “My Plugins” menu in the WordPress administration area. By clicking on it, you can configure and save a text option. All data is securely stored via the WordPress API.wp_optionsIn the table.
Add front-end functionality to the plugin: Create shortcodes.
Backend functionality is essential, but plugins often also need to affect the website’s front end. Creating shortcodes is an excellent way to integrate plugin features into articles, pages, or widgets.
Register a simple short code.
We registered a name called…[my_greeting]This is a short code used to display a greeting message on the front end.add_shortcode()Function.
Add the following content to the main file or a dedicated functional file:
// 注册短代码
function mfp_greeting_shortcode($atts, $content = null) {
// 使用shortcode_atts设置默认属性并合并用户输入
$atts = shortcode_atts(
array(
'name' => '访客', // 默认值
),
$atts,
'my_greeting' // 短代码名称
);
// 获取插件选项中存储的文本
$options = get_option('mfp_options');
$custom_text = $options['mfp_text_field'] ?? '';
// 构造输出
$output = '<div class="mfp-greeting">'$output = '<p>Hello, '. esc_html($atts['name'])'. ‘! Welcome to our website.</p>';
if (!empty($custom_text)) {
$output .= '<p><strong>Custom Message:</strong>'. esc_html($custom_text)'.'</p>'$output = '</div>';
// 返回输出内容,而不是直接echo
return $output;
}
add_shortcode('my_greeting', 'mfp_greeting_shortcode'); Now, users can enter text in the article editor.[my_greeting name="张三"]The front end will render personalized greeting messages, and if “sample text” has been set in the back end, it will also be displayed. This approach effectively connects the settings from the back end with the output on the front end.
summarize
Through the steps outlined above, we have completed a WordPress plugin with full functionality. We started from scratch, creating the basic files and structure of the plugin, and used…add_menu_page()We have built a secure backend settings page using the Settings API, and it is accessible through…add_shortcode()The front-end functionality has been implemented. This process encompasses the core steps of plugin development: planning, initialization, integration with the backend API, data processing, and providing front-end interfaces.
After gaining a thorough understanding of these fundamental concepts, you can move on to explore more advanced topics, such as creating custom article types, metadata (Meta Boxes), customizing database tables, REST API endpoints, handling AJAX requests, and internationalizing plugins. Remember that adhering to WordPress coding standards and best practices is crucial for developing high-quality, maintainable plugins.
FAQ Frequently Asked Questions
What PHP knowledge is essential for plugin development?
You need to have at least a basic understanding of PHP syntax, including variables, arrays, functions, conditional statements, and loops. Knowledge of object-oriented programming (OOP) is very helpful for building medium to large plugins. In addition, it is essential to understand how WordPress loads plugins, as well as how to use global variables and functions securely.
如何调试自己开发的WordPress插件
First, make sure that...wp-config.phpThe file is open in the programWP_DEBUGandWP_DEBUG_LOGIn this way, the error messages will be recorded in the log file. Secondly, it is possible to use…error_log()The function outputs debugging information. For complex logic, professional debugging tools such as Xdebug can be used to execute the code step by step.
How to ensure the security of a plugin when developing it?
Always validate and clean user input. Use the built-in functions in WordPress, such as…esc_html(), esc_attr(), sanitize_text_field()andwp_kses()Handle the output. Use something other than CE.wp_nonce_field()This is to prevent Cross-Site Request Forgery (CSRF). For database operations, use…$wpdbThe methods provided by the class, or their usage.prepare()Statements to prevent SQL injection.
Should plugins be developed locally or on an online server?
It is highly recommended to carry out the main development work in a local development environment (such as Local or XAMPP). Local environments respond quickly, are not affected by the internet, and allow for free testing and experimentation without impacting the live website. Once the basic functionality is completed, deploy the application to an online testing environment for final compatibility testing.
How to publish your own plugin to the WordPress official repository
You need to visit WordPress.org, register a developer account, and submit your plugin code via Subversion (SVN). The plugin must comply with the official code standards and directory structure requirements, and must include the necessary files and information.readme.txtOnce the file has been approved, users around the world will be able to directly search for and install your plugin from the backend.
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.
- Why use WooCommerce to build an online store?
- Why Choose WordPress: The Top Ten Core Advantages of an Open-Source CMS
- Master WooCommerce in Ten Minutes: A Guide to Building an E-commerce Website from Scratch to Profit
- WooCommerce Complete Guide: An Advanced E-commerce Configuration Tutorial from Installation to Live Deployment
- What is WordPress? A comprehensive introduction to a content management system