Preparing the WordPress Plugin Development Environment
Before you start writing code, having a suitable development environment is crucial. It not only allows you to work efficiently but also simulates the real production environment, helping to avoid inconsistencies between your local setup and the online environment. A typical development environment should include a local server, a code editor, and debugging tools.
First of all, you need a local server environment that can run WordPress. It is recommended to use an integrated development environment package, such as Laragon, XAMPP, or Local by Flywheel. These tools can install Apache/Nginx, PHP, and MySQL with just one click, eliminating the need for complicated configuration processes. Make sure that your PHP version is compatible with the current mainstream version of WordPress; PHP 7.4 or higher is generally recommended. Additionally, in the WordPress administration panel, under “Tools” -> “Site Health,” check to ensure that there are no critical issues that could affect plugin development.
Secondly, choose a powerful code editor. Visual Studio Code is a very popular option at the moment; it’s lightweight, free, and comes with a wealth of extensions, such as PHP Intelephense (for intelligent code suggestions) and WordPress Snippet (for code snippets). Another classic choice is PhpStorm, which offers more integrated support for WordPress development, but it is a paid software.
Recommended Reading Zero to One: The Complete Guide to WordPress Plugin Development and Best Practices。
Finally, enabling debug mode is an essential step in the development process. This can be done by modifying the files located in the WordPress root directory.wp-config.phpFor files, you can enable detailed error reporting, which is crucial for identifying and fixing issues in the code. Locate the file where the definitions are made.WP_DEBUGIn the place where the constants are defined, you can add the following code:
// 启用 WordPress 调试模式
define( 'WP_DEBUG', true );
// 将错误记录到 /wp-content/debug.log 文件
define( 'WP_DEBUG_LOG', true );
// 在页面上显示错误(开发环境推荐,生产环境必须关闭)
define( 'WP_DEBUG_DISPLAY', true ); Create your first plug-in file
A WordPress plugin can be as simple as having just one file. All plugins must be stored in a specific directory within WordPress./wp-content/plugins/Within the directory, each plugin can have its own subdirectory, which helps to organize more complex code structures.
Plugin header comments
Every plugin’s main file must start with standardized PHP header comments; this is how WordPress identifies plugin information. Create a new file and name it…my-first-plugin.phpAnd place it inside./wp-content/plugins/my-first-plugin/The file is located in the folder. The content of the file is as follows:
<?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
*/ This comment provides all the meta-information about the plugin that is displayed on the “Plugins” page in the WordPress administration panel.Text DomainandDomain PathUsed for the internationalization (i18n) preparation of plugins.
Implement a simple function
Now, let’s add a simple feature to this plugin: it will automatically add a line of custom text at the end of the article content. We will use WordPress’s built-in functionality for this.the_contentFilter hook. The one you just created…my-first-plugin.phpBelow the header comments of the file, add the following function:
Recommended Reading Mastering WordPress Plugin Development: Building Custom Features from Scratch。
// 在文章内容末尾添加自定义文本
function my_first_plugin_add_footer_text( $content ) {
// 确保只在主循环的单篇文章页面执行
if ( is_single() && in_the_loop() && is_main_query() ) {
$footer_text = '<p><em>Thank you for reading! This article is brought to you by “My First Plugin”.</em></p>';
$content .= $footer_text;
}
return $content;
}
add_filter( 'the_content', 'my_first_plugin_add_footer_text' ); After saving the file, log in to your WordPress administration panel and navigate to the “Plugins” page. You should see a plugin named “My First Plugin.” Activate it, then browse a blog post; you will notice that the text we defined has been successfully added at the bottom of the post content.
Using the WordPress core API
During in-depth development, you will frequently interact with the various APIs provided by WordPress. Among these, the most crucial component is the Hooks system, which consists of Actions and Filters.
Understand action hooks
Action hooks allow you to execute custom code at specific moments in time. For example, when an article is published, you might want to send an email notification. This is something you can utilize.publish_postActions. The following example demonstrates how to create a feature that logs information to the error log when an article is published:
// 定义文章发布时执行的动作函数
function my_first_plugin_log_post_published( $post_id, $post ) {
// 避免无限循环和非文章类型
if ( wp_is_post_revision( $post_id ) || $post->post_type != ‘post’ ) {
return;
}
// 记录日志
error_log( “文章 ID {$post_id} 已发布,标题为:{$post->post_title}” );
}
// 将函数挂载到 publish_post 动作钩子上
add_action( ‘publish_post’, ‘my_first_plugin_log_post_published’, 10, 2 ); functionadd_actionThe third parameter is the priority (default value is 10); the smaller the number, the higher the priority. The fourth parameter indicates the number of arguments that the function accepts.
Understanding Filter Hooks
Filter hooks are used to modify data. In the “Creating Your First Plugin File” section, the ones we used…the_contentIt’s just a filter hook. It receives the original content and allows you to modify it before returning it. Another common example is modifying the length of an article’s summary.
// 修改摘要的默认字数
function my_first_plugin_custom_excerpt_length( $length ) {
return 30; // 将摘要字数改为30字
}
add_filter( ‘excerpt_length’, ‘my_first_plugin_custom_excerpt_length’ ); Add an entry menu.
In order to interact with users, we usually need to add a menu page to the management sidebar in the WordPress backend. This can be achieved by...add_menu_pageFunction implementation: The following code adds a top-level settings page to the plugin.
Recommended Reading WordPress Plugin Development Guide: Building High-Quality WordPress Extensions from Scratch。
// 创建插件管理菜单
function my_first_plugin_add_admin_menu() {
add_menu_page(
‘我的第一个插件设置’, // 页面标题
‘我的插件’, // 菜单标题
‘manage_options’, // 所需权限
‘my-first-plugin’, // 菜单slug
‘my_first_plugin_settings_page’, // 回调函数,用于输出页面内容
‘dashicons-admin-plugins’, // 图标(可选)
100 // 菜单位置(可选)
);
}
add_action( ‘admin_menu’, ‘my_first_plugin_add_admin_menu’ );
// 设置页面的回调函数
function my_first_plugin_settings_page() {
?>
<div class="“wrap”">
<h1>My first plugin settings</h1>
<p>This is the plugin settings page. In the future, you will be able to add forms and options here.</p>
</div>
<?php
} Plugin security and best practices
When developing plugins for others to use, security and code quality cannot be overlooked. Following best practices can protect websites from attacks and ensure that the plugins are compatible and easy to maintain.
Data Validation and Escaping
Never trust data entered by users or data retrieved from a database. Data must be escaped before being sent to the browser, and it must be validated and cleaned before being saved to the database. WordPress provides a large number of helper functions to assist with this process.
- Escape output: Use
esc_html()、esc_attr()、esc_url()andwp_kses_post()Functions such as these escape data based on the context. - Verify the input: Use
sanitize_text_field()、sanitize_email()、intval()Functions such as these are used to clean the form data submitted by users.
For example, when setting up the page to process form data:
$user_input = $_POST[‘some_field’] ?? ‘’; // 使用空合并运算符提供默认值
$clean_input = sanitize_text_field( $user_input ); // 清理数据
update_option( ‘my_plugin_option’, $clean_input ); // 安全存储 \nUse non-CE and permission checks
When processing form requests (especially those from admin-ajax.php or admin-post.php), it is essential to use…wp_verify_nonce()This is to verify the legitimacy of the request and prevent Cross-Site Request Forgery (CSRF) attacks. At the same time, use…current_user_can()Check whether the current user has the necessary permissions to perform the operation.
function my_first_plugin_handle_form_submit() {
// 1. 检查nonce
if ( ! isset( $_POST[‘my_nonce_field’] ) || ! wp_verify_nonce( $_POST[‘my_nonce_field’], ‘my_action’ ) ) {
wp_die( ‘安全校验失败!’ );
}
// 2. 检查权限
if ( ! current_user_can( ‘manage_options’ ) ) {
wp_die( ‘权限不足!’ );
}
// 3. 安全地处理数据…
} Code Organization and Internationalization
For complex plugins, it is recommended to use object-oriented programming (OOP) to organize the code, modularizing functions into classes. This improves the readability and reusability of the code.
At the same time, prepare for internationalization of the plugin from the very beginning. This means that all user-facing strings should use WordPress’s translation functions.__()、_e()Packaging it up. Looking at the comments at the top of the plugin, we have already defined the necessary settings.Text DomainThis is how it should be used in the code:
$message = __( ‘感谢阅读!本文由“我的第一个插件”为您呈现。’, ‘my-first-plugin’ ); Then, you can use tools like Poedit to create it..potTemplate files, used by translators to generate content in different languages..moThe document.
summarize
By following this guide, you have completed the essential steps of creating a WordPress plugin from scratch. You have learned how to set up a development environment, create plugin files that include standard header comments, and utilize WordPress’s powerful action and filter hook systems to add functionality. We also discussed how to securely add administrative menus and handle data, emphasizing the importance of security and internationalization. Plugin development is a continuous process of learning and practice; the key lies in understanding WordPress’s hook systems and security best practices. Next, you can try developing more complex features, such as creating custom database tables, adding shortcodes, widgets, or REST API endpoints, and gradually build a professional-grade plugin with comprehensive functionality and robust code.
FAQ Frequently Asked Questions
Does a plugin have to be placed in a separate folder?
No, a plugin can simply be a standalone component..phpThe files can be placed directly there./wp-content/plugins/The files are located in the directory. However, for any plugins that contain multiple files, resources (such as JS and CSS), or need to have their files translated, it is highly recommended to use a separate folder to store all related files. This will make the project structure clearer and easier to manage.
How can I save the settings of my plugin in the database?
WordPress provides a very convenient Options API. You can use it.add_option()、get_option()andupdate_option()Functions are used to add, retrieve, and update plugin settings. This data is securely stored within WordPress.wp_optionsIn database tables, for large amounts of structured data, it may be advisable to serialize the data into arrays or JSON strings before storing it.
Will the plugins I develop conflict with other plugins?
It’s possible, especially when the plugin uses common hooks, function names, or class names. To avoid conflicts, the best practices are: to add a unique prefix to all your functions, classes, and variables (for example, using the plugin’s abbreviation or name); to use the plugin’s slug as a namespace (real namespaces are available in PHP 5.3+); and to choose the appropriate priority when using hooks to ensure that the execution order meets your expectations.
Which WordPress versions does the plugin need to be compatible with?
It depends on your target users. Generally, it is recommended to ensure compatibility with the current major version as well as one or two previous versions. You can refer to the documentation for the plugin to find out the specific requirements.readme.txtThe file has been processed successfully.Requires at least:Use fields to specify the minimum required version of WordPress. During the development process, avoid using functions that are only available in newer versions of WordPress.function_exists()Conduct compatibility checks to expand the range of applications for the plugin.
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.
- WordPress Plugin Development Guide: Creating Your First Custom Plugin from Scratch
- Becoming a WordPress Plugin Developer: A Complete Guide from Scratch
- WordPress Plugin Development Complete Guide: From Beginner to Expert – Creating Professional Extensions
- WordPress Plugin Development: From Beginner to Expert – Building Your First Custom Plugin
- From Zero to One: A Comprehensive Guide to Developing Your First WordPress Plugin Step by Step