Preparing the WordPress Plugin Development Environment
Before starting to write code, a stable and isolated development environment is essential. This not only protects your production site but also allows you to test and debug your code freely. The most recommended approach is to use a local development environment, such as Local by Flywheel, XAMPP, or MAMP. These tools can install the PHP, MySQL, and web servers required for WordPress on your local computer with just one click.
Next, you need to enable the debug mode in your local WordPress installation. This will help you quickly identify errors during the development process. Open the file located in the WordPress root directory… wp-config.php For the file, find or add the following constant definitions:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false ); After making this setting, all error and warning messages will be recorded. /wp-content/debug.log The file content will be stored within the system and not directly displayed on the page, thus avoiding any impact on the end-users.
Recommended Reading WordPress Plugin Development Beginner's Guide: Creating Your First Custom Plugin from Scratch。
Finally, you need a code editor. Visual Studio Code, PhpStorm, or Sublime Text are all excellent choices, as they offer excellent syntax highlighting and code suggestions for PHP and WordPress development. Make sure your editor allows you to easily access the project files on your local server.
Create your first plugin
A WordPress plugin is essentially one or more components that are located within the WordPress framework. wp-content/plugins The PHP files in the directory. Each plugin must have a main file, and the header of this file must contain standard plugin information comments so that WordPress can recognize it.
Write the header information for the plug-in
In your wp-content/plugins Inside the directory, create a new folder, for example… my-first-pluginWithin this folder, create the main file my-first-plugin.phpThe beginning of the file must contain a comment in the following format:
<?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
*/ The “Plugin Name” in this comment is required; all other fields are optional. WordPress will read this information and display it on the “Plugins” management page in the background.
Implement a simple function
Now, let’s add the first actual feature to this plugin: automatically adding a custom piece of text at the end of the article content. We will use… the_content This Filter Hook.
Recommended Reading Introduction to WordPress Plugin Development: From Beginner to Expert: Sharing Practical Experience and Core Techniques。
Below the header comments, add the following code:
function myfp_add_text_to_content( $content ) {
if ( is_single() && in_the_loop() && is_main_query() ) {
$custom_text = '<p><em>Thank you for reading this article, brought to you by “My First Plugin”.</em></p>'function myfp_add_text_to_content( $content ) {
if ( is_singular( 'post' ) ) {
$custom_text = get_post_custom( $post_id );
if ( ! empty( $custom_text[ 'my_custom_field' ] ) ) {
$content .= $custom_text[ 'my_custom_field' ];
}
}
return $content;
}
add_filter( 'the_content', 'myfp_add_text_to_content' ); After saving the file, go to the “Plugins” page in the WordPress administration dashboard. You should see “My First Plugin” there. Activate it, and then check an article on your website; you will notice that the text we defined has been added at the end of the article. In this code snippet…myfp_add_text_to_content It is a function that we have defined ourselves.add_filter() Mount it to the_content It’s displayed on the hook. The conditional checks within the function ensure that this text is only shown in the main loop of the individual article pages on the front end.
Understanding the core mechanisms of WordPress plugins
The powerful and flexible foundation of WordPress plugins lies in its Hook mechanism. Hooks enable you to insert your own code at specific points in the execution of WordPress’s core code, allowing you to modify or enhance its default behavior. There are mainly two types of hooks: Action Hooks and Filter Hooks.
Action hooks and filter hooks
Action hooks allow you to execute custom code when a specific event occurs, such as after an article is published or when a management page is loaded. They do not require a return value. add_action() A function is used to perform certain actions, such as executing an operation when a plugin is activated.
function myfp_plugin_activation_task() {
// 创建数据库表、初始化选项等
update_option( 'myfp_plugin_installed', '2026-01-01' );
}
register_activation_hook( __FILE__, 'myfp_plugin_activation_task' ); The following elements/technologies were used here: register_activation_hookIt is a special action hook that is specifically designed for plugin activation.
The “Filter” hook allows you to modify the data that is passed to it. It requires the function to receive a value and must return a modified value. The example we used earlier, where we modified the content of an article, is a typical use case for a filter. Another example is modifying the length of an article excerpt.
Recommended Reading Master WordPress Plugin Development: A Complete Practical Guide from Zero to One。
function myfp_custom_excerpt_length( $length ) {
return 20; // 将摘录长度改为20个单词
}
add_filter( 'excerpt_length', 'myfp_custom_excerpt_length' ); Use shortcodes to add dynamic content.
In addition to hooks, shortcodes are another powerful tool for plugins to interact with content. They allow users to insert a simple tag into an article or page in order to enable certain functionality. [my_shortcode]This is used to invoke the complex content generated by the plugin.
Creating a short code is very simple; you can use… add_shortcode() Functions. For example, here’s a short piece of code that displays the current time:
function myfp_current_time_shortcode( $atts ) {
$atts = shortcode_atts( array(
'format' => 'Y-m-d H:i:s',
), $atts, 'current_time' );
return date( $atts['format'] );
}
add_shortcode( 'current_time', 'myfp_current_time_shortcode' ); Users can enter text in the editor. [current_time format="H:i"] Only display the hours and minutes.
Add a management page for the plugin.
Many plugins require the provision of configuration options, which is usually achieved through the management menu pages in the WordPress backend. WordPress offers a series of functions for adding top-level menu items or sub-menu items.
Create a plugin settings page.
We will add a simple settings page for the plugin to manage the text content that was previously added at the end of the articles. First, use… add_menu_page() Or add_options_page() A function is used to register the page. Typically, simple plugins will add the page to the “Settings” submenu.
Add the following code to the main file of the plugin:
function myfp_add_admin_menu() {
add_options_page(
'我的第一个插件设置', // 页面标题
'我的插件设置', // 菜单标题
'manage_options', // 所需权限
'myfp-settings', // 菜单slug
'myfp_settings_page_html' // 用于输出页面内容的回调函数
);
}
add_action( 'admin_menu', 'myfp_add_admin_menu' ); This code tells WordPress that, when building the admin menu,admin_menu Action), execution myfp_add_admin_menu A function is used to add a new page.
Build a settings page form
Next, we need to define myfp_settings_page_html The function is used to generate the HTML content for the page and to handle the saving of form data. To store the settings securely, we use WordPress’s built-in functionality. options API (Application Programming Interface).
function myfp_settings_page_html() {
// 检查用户权限
if ( !current_user_can( 'manage_options' ) ) {
return;
}
// 处理表单提交
if ( isset( $_POST['myfp_footer_text'] ) ) {
update_option( 'myfp_footer_text', sanitize_textarea_field( $_POST['myfp_footer_text'] ) );
echo '<div class="notice notice-success"><p>Settings have been saved!</p></div>';
}
// 获取现有值
$current_text = get_option( 'myfp_footer_text', '感谢阅读本文,由“我的第一个插件”为您呈现。' );
?>
<div class="wrap">
<h1>My first plugin settings</h1>
<form method="post" action="">
<?php wp_nonce_field( 'myfp_settings_action', 'myfp_settings_nonce' ); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="footer_text">The text at the bottom of the article</label></th>
<td>
<textarea name="myfp_footer_text" id="footer_text" rows="4" cols="50" class="large-text"><?php echo esc_textarea( $current_text ); ?></textarea>
<p class="description">This text will be displayed at the end of each article.</p>
</td>
</tr>
</table>
<?php submit_button(); ?>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
<?php
} Finally, remember to modify the function that previously filtered the article content so that it takes into account the new options. myfp_footer_text The text is read from a file, rather than using hardcoded strings. With this approach, a backend settings page with basic management functions is completed.
summarize
By following the steps in this article, you have successfully created a fully functional WordPress plugin from scratch. You have learned how to set up a development environment, build the basic structure of a plugin, use WordPress’s core hook mechanism (actions and filters) to extend its functionality, implement shortcodes, and create a backend administration interface. The core of plugin development lies in understanding how hooks and event-driven programming work, which allows you to customize WordPress’s behavior in depth without modifying the core code. Remember that a well-structured codebase, secure handling of input and output, and support for internationalization are the foundations of developing high-quality plugins. Next, you can try adding more features to your plugin, such as custom post types, widgets, or REST API endpoints, and continue to explore the endless possibilities of the WordPress ecosystem.
FAQ Frequently Asked Questions
Does a plugin have to contain only one PHP file?
Not necessarily. A plugin can consist of a single PHP file; however, for more complex plugins, a modular structure is recommended. You can split different functions into separate classes or files, with the main file responsible for only including these files and initializing the plugin. This makes the code easier to maintain and organize. For example, you could create… includes/ The directory stores functional classes.admin/ The directory contains the code related to the backend.public/ The directory contains the front-end logic.
How to safely handle user input in plugins?
When processing user input (such as form data or URL parameters), it is essential to perform validation, sanitization, and escaping. For data that is stored in a database, use appropriate methods to ensure the security and integrity of the data. sanitize_text_field()、sanitize_textarea_field()、intval() Use functions such as cleaning to process the data. When outputting the data to an HTML page, employ these cleaning processes. esc_html()、esc_attr()、esc_url() Or wp_kses() Escape the characters to prevent Cross-Site Scripting (XSS) attacks.
How to debug code during plugin development?
In addition to enabling… WP_DEBUG In addition, you can also use… error_log() The function records custom information in the debug log. This is useful for checking the values of variables.var_dump() Or print_r() Combined with die() It’s a quick but rough method. It’s recommended to use the built-in features of WordPress instead. wp_die() and wp_send_json()(For AJAX debugging.) Additionally, using professional debugging plugins such as Query Monitor allows for a more intuitive view of runtime information related to database queries, hooks, scripts, and more.
How can I make my plugin support multiple languages?
To make a plugin support internationalization (i18n), you need to use WordPress’s translation functions. First, make sure to set the necessary options correctly in the comments at the top of the plugin file. Text Domain(For example, ‘my-first-plugin’). In the code, use this format for all strings that are displayed to the user. () Or _e() The function is wrapped, for example… ( ‘Hello World’, ‘my-first-plugin’ )Then, use tools such as Poedit to generate the content. .pot Template files, which translators can use to create translations in different languages. .po and .mo The files are stored within the plugin. languages/ In the folder.
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