Preparatory work and environment setup
Before you start writing code, you need a suitable development environment. This includes a local WordPress installation, a code editor, and basic knowledge of PHP. It is recommended to use XAMPP, MAMP, or Local by Flywheel to quickly set up a local WordPress environment. Make sure that your PHP version meets the official WordPress requirements, which is usually PHP 7.4 or a later version.
A plugin is essentially one or more PHP files that are placed within the WordPress framework.wp-content/pluginsThe plugins are all listed in the directory. Each plugin must have a unique name, and the header of its main file must contain standard plugin information comments. This is the basis for WordPress to recognize the plugins.
Create your first plug-in file
Firstly, inwp-content/pluginsCreate a new folder within the directory, for example…my-first-pluginThen create the main PHP file inside that folder; it usually has the same name as the folder.my-first-plugin.phpIn this file, you need to write the plugin header information.
Recommended Reading A Complete Guide to WordPress Plugin Development: Building Your First Plugin from Scratch。
<?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
*/ After saving the file, go to the “Plugins” page in the WordPress administration dashboard. You should see “My First Plugin” listed in the plugin directory. Activate it; although it doesn’t have any functionality yet, this indicates that your plugin has been successfully loaded by WordPress.
Understanding the Core Mechanisms of WordPress: Hooks and Filters
The powerful scalability of WordPress stems from its event-driven architecture, with the core component being “Hooks.” There are two types of Hooks: Actions and Filters. Understanding how they work is crucial for developing effective plugins.
Action hooks allow you to insert and execute your own code at specific moments in time, such as when an article is published or a page is loaded. For example, you can send an email when an article is published. You can use them to automate tasks like this.add_action()The function mounts your custom function to the specified action hook.
Filter hooks allow you to modify data. Before the data is used (such as being saved to a database or displayed in a browser), you can intercept and alter it. For example, you can change the title of an article or the content of a comment. You can use these hooks to make necessary adjustments to the data.add_filter()A function is used to apply the filter.
Use action hooks to add functionality.
Suppose we want to add a line of custom text to the footer of the website’s administration backend page. WordPress provides a feature called…admin_footerAction hook. We can add the following code to the main plugin file:
Recommended Reading WordPress Plugin Development Beginner’s Guide: Building Your First Functional Plugin from Scratch。
// 定义一个在管理后台页脚显示信息的函数
function myplugin_display_admin_footer_text() {
echo '<p>Thank you for using “My First Plugin”!</p>';
}
// 将函数挂载到 admin_footer 动作钩子
add_action( 'admin_footer', 'myplugin_display_admin_footer_text' ); Save the file and refresh the WordPress administration page. Scroll to the bottom of the page; you should see the text that you added. This is a basic example of how action hooks work: they allow you to execute code at specific locations within the WordPress framework.
Use filters to modify the content.
Now, let’s try to modify all the article titles by adding a trademark symbol at the end of each title. We can use…the_titleFilters.
// 定义一个修改文章标题的函数
function myplugin_modify_post_title( $title, $post_id ) {
// 确保只在主循环且非管理后台中修改
if ( ! is_admin() && in_the_loop() ) {
$title = $title . ' ™';
}
return $title;
}
// 将函数挂载到 the_title 过滤器钩子,参数2表示接受2个参数
add_filter( 'the_title', 'myplugin_modify_post_title', 10, 2 ); This code checks whether the current environment is within the main loop for handling frontend articles. If so, it adds the “™” symbol after the title.10It represents the priority (the smaller the number, the earlier the task is executed).2This indicates that our function accepts two parameters (the original ones).$titleand$post_id)。
Building plugin functionality: Creating a management menu and settings page
A mature plugin usually needs to provide configuration options in the WordPress administration panel. This involves creating a dedicated management menu page for the plugin. WordPress offers a rich set of API functions to achieve this functionality. For example…add_menu_page()andadd_options_page()。
Add a top-level management menu.
We will add a separate top-level menu for the plugin. This is usually done in…admin_menuThe action is completed within the hook. We will create a function to define the menu and the pages.
// 定义添加管理菜单的函数
function myplugin_add_admin_menu() {
add_menu_page(
'我的插件设置', // 页面标题
'我的插件', // 菜单标题
'manage_options', // 所需权限(管理员)
'myplugin-settings-page', // 菜单slug(唯一标识)
'myplugin_display_settings_page', // 用于显示页面内容的回调函数
'dashicons-admin-generic', // 菜单图标(Dashicons)
30 // 菜单位置
);
}
// 将函数挂载到 admin_menu 钩子
add_action( ‘admin_menu’, ‘myplugin_add_admin_menu’ ); Next, we need to define the callback function.myplugin_display_settings_page()This is used to render the HTML content of the settings page.
Recommended Reading From Beginner to Expert: A Complete Guide to Developing WordPress Plugins and Building Custom Features。
// 定义设置页面的显示内容
function myplugin_display_settings_page() {
?>
<div class="wrap">
<h1>My plugin settings</h1>
<form method="post" action="/en/options.php/" data-trp-original-action="options.php">
<?php
// 输出设置字段、安全nonce等
settings_fields( ‘myplugin_settings_group’ );
do_settings_sections( ‘myplugin-settings-page’ );
submit_button();
?>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
<?php
} Registration settings, fields, and partitions
To securely process form data, we need to use WordPress’s Settings API. This involves registering settings, adding settings sections, and creating fields.
// 初始化插件设置
function myplugin_settings_init() {
// 1. 注册一个设置(存储在wp_options表中)
register_setting(
‘myplugin_settings_group’, // 设置组名,与 settings_fields() 对应
‘myplugin_options’ // 存储在数据库中的选项名
);
// 2. 添加一个设置分区
add_settings_section(
‘myplugin_section_basic’, // 分区ID
‘基础设置’, // 分区标题
‘myplugin_section_basic_callback’, // 分区介绍的回调函数
‘myplugin-settings-page’ // 所属页面的slug
);
// 3. 为分区添加一个字段
add_settings_field(
‘myplugin_field_message’, // 字段ID
‘欢迎信息’, // 字段标签
‘myplugin_field_message_callback’, // 渲染字段HTML的回调函数
‘myplugin-settings-page’, // 所属页面的slug
‘myplugin_section_basic’ // 所属分区的ID
);
}
add_action( ‘admin_init’, ‘myplugin_settings_init’ );
// 分区介绍的回调函数
function myplugin_section_basic_callback() {
echo ‘<p>Configure the basic information for the plugin.</p>’;
}
// 字段渲染的回调函数
function myplugin_field_message_callback() {
// 从数据库获取现有值
$options = get_option( ‘myplugin_options’ );
$value = $options[‘message’] ?? ‘’; // PHP 7.0+ 空合并运算符
// 输出输入框
echo ‘<input type="“text”" name="“myplugin_options[message]”" value="“‘" . esc_attr( $value ) ‘” class ="“regular-text”" />‘;
} Now, your plugin has a complete management settings page that complies with WordPress standards, allowing you to safely save and retrieve configuration options.
Best Practices for Plugin Internationalization and Security
To make your plugin available to users around the world, internationalization (i18n) is an essential step. At the same time, following security guidelines is the foundation for protecting both you and the user websites from attacks.
Implementing text internationalization
WordPress is widely used.__()、_e()Use functions such as `translate()` to implement the translation. First, you need to make sure that the necessary settings have been correctly configured at the top of the plugin.Text Domain(For example:my-first-pluginThen, wrap all the user-facing strings with the translation function.
// 在插件代码中,将硬编码的文本替换
// 修改前:echo ‘<p>Thank you for using “My First Plugin”!</p>’;
// 修改后:
function myplugin_display_admin_footer_text() {
echo ‘<p>‘ . esc_html__( ‘感谢使用“我的第一个插件”!’, ‘my-first-plugin’ ) . ‘</p>’;
} Next, you will need to use tools such as Poedit to generate the necessary files..pot(The template file is placed in the plugin.)languagesIn the folder. The translator can create the corresponding files..poAnd the compiled version.moFinally, use the file during the plugin initialization process.load_plugin_textdomain()Function loading translation.
function myplugin_load_textdomain() {
load_plugin_textdomain( ‘my-first-plugin’, false, dirname( plugin_basename( __FILE__ ) ) . ‘/languages/’ );
}
add_action( ‘plugins_loaded’, ‘myplugin_load_textdomain’ ); Follow security coding guidelines.
Security is of utmost importance. First and foremost, never trust any data entered by users. All data coming from users or external sources should be treated with caution.$_GET, $_POST, $_COOKIEAll of them must be verified, cleaned, and escaped.
- Escape output: When outputting data to HTML, JavaScript, or a URL, use the appropriate escape functions.
// 输出到HTML属性
echo ‘<input value="“‘" . esc_attr( $value ) ‘“ />‘;
// 输出到HTML内容
echo ‘<p>‘ . esc_html( $text ) . ‘</p>’;
// 输出到JavaScript变量
echo ‘<script>var msg = “‘ . esc_js( $message ) . ‘“;</script>’;
// 输出到URL
echo ‘<a href="/en/“‘/" . esc_url( $url ) ‘“>link</a>’; - Verify the input: Check whether the data conforms to the expected format (for example, whether it is an email address or a number).
if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
// 不是有效的邮箱地址
wp_die( ‘无效的邮箱格式。’ );
} - Ability Check: Before performing management operations, verify whether the current user has the necessary permissions.
if ( ! current_user_can( ‘manage_options’ ) ) {
wp_die( ‘你没有执行此操作的权限。’ );
} - Nonce Verification: For operations that involve state changes (such as form submissions or AJAX requests), a Nonce (a unique, one-time numerical value) is used to prevent Cross-Site Request Forgery (CSRF) attacks.
// 在表单中输出nonce字段
wp_nonce_field( ‘myplugin_action’, ‘myplugin_nonce’ );
// 在处理请求时验证nonce
if ( ! isset( $_POST[‘myplugin_nonce’] ) || ! wp_verify_nonce( $_POST[‘myplugin_nonce’], ‘myplugin_action’ ) ) {
wp_die( ‘安全校验失败。’ );
} summarize
By following this guide, you have completed the entire process from creating basic plugin files, understanding and utilizing WordPress’s core hook system, building a backend administration interface, to implementing internationalization and applying basic security practices. You have now acquired the essential skills required to develop a WordPress plugin that is feature-rich, well-structured, and secure. The essence of plugin development lies in making effective use of action and filter hooks to extend WordPress’s functionality, while always prioritizing security and maintainability. Next, you can explore more complex APIs, such as custom database tables, AJAX interactions, or REST API endpoints, in order to build even more powerful tools.
FAQ Frequently Asked Questions
What prerequisites are required to develop a WordPress plugin for ###?
You need to have a basic understanding of PHP programming. It will also be very helpful if you are familiar with HTML, CSS, and JavaScript (especially jQuery). Most importantly, you should have a preliminary understanding of the basic structure of WordPress, including concepts such as themes, plugins, article types, and user roles. This guide assumes that you already possess these foundational skills.
How to debug my WordPress plugin?
First of all, make sure that your…wp-config.phpIn the document,WP_DEBUGThe constant is set totrueThis will display PHP errors, warnings, and notifications on the page. Secondly, it is possible to use…error_log()The function writes debug information to the server’s error log. For more advanced debugging, you can consider using specialized debugging plugins, such as Query Monitor, which allows you to view detailed information about database queries, hook executions, script loads, and more.
How should I distribute the plugins I have developed?
For personal use or small-scale sharing, you can simply package the ZIP file. If you want to release it publicly, there are two main approaches: First, submit it to the official WordPress plugin directory (WordPress.org), which requires following its submission guidelines and code standards, but can gain the most exposure; Second, distribute it through your own website or third-party marketplaces (such as CodeCanyon). Before submitting to the official directory, please ensure the quality and security of the code.
How can I add custom article types or taxonomies to my plugin?
You can useregister_post_type()Function to create a custom post type (CPT), usingregister_taxonomy()Use functions to create custom taxonomies. It’s best to perform these operations…initThe actions are executed within the action hooks. The WordPress Codex and Developer Handbook provide detailed descriptions of the parameters for these two functions; this is a powerful way to extend the functionality of WordPress’s content management system.
How can function names in plugins be avoided from conflicting with those in other plugins?
To prevent conflicts between function names, class names, or constant names, the best practice is to use namespaces (PHP 5.3+). If your plugin needs to support older PHP versions or if you want to maintain maximum compatibility, you can add a unique prefix to all identifiers. For example, you can use the plugin name or an abbreviation as the prefix.myplugin_function_name、MyPlugin_ClassNameOrMYPLUGIN_CONSTANTThe example code in this guide all uses the prefixing method.
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.
- WooCommerce Plugin Configuration and Usage Guide: Building an E-commerce Website from Scratch
- Preface: Why choose WordPress for development?
- Why choose WooCommerce as your e-commerce solution?
- WooCommerce Complete Guide: Building Your Online Store and Sales Strategy from Scratch
- Mastering WordPress Theme Development: A Comprehensive Guide to Building Professional Websites from Scratch