Preparatory work and environment setup
Before you start writing code, you need a suitable development environment. This includes a local installation of WordPress and a code editor. It is recommended to use XAMPP, Local by Flywheel, or Docker to set up a local server environment. Make sure your WordPress is up to date to take advantage of the latest APIs and security features.
You need to understand the basic structure of WordPress plugins. The smallest plugin requires at least one main file, which is a PHP file with specific header comments. The name of this file is usually… your-plugin-name.phpIt tells WordPress that this is a plugin, and provides information such as the name, description, version, and author.
In the code editor, create a new folder for your plugin project, for example: my-first-pluginInside this folder, create the main PHP file.
Recommended Reading Starting from scratch: The ultimate guide and practical tutorial for WordPress plugin development。
Create your first plug-in file
Now, let’s start creating the main file for the plugin. This file serves as the entry point for the plugin, and it announces its presence to WordPress through the comment block at the top of the file.
Write the header information for the plug-in
In the PHP file you just created, you need to add the standard plugin header. For example, a plugin named “Site Greeting” can start like this:
<?php
/**
* Plugin Name: 站点问候语
* Plugin URI: https://example.com/my-first-plugin
* Description: 一个简单的插件,用于在网站前台显示自定义问候语。
* Version: 1.0.0
* Author: 你的名字
* License: GPL v2 or later
* Text Domain: my-first-plugin
* Domain Path: /languages
*/ WordPress will perform a scan. wp-content/plugins Read the specific comment information from all PHP files in the directory and display it on the backend plugin management page. Text Domain Used for internationalization.Domain Path The location of the language file has been specified.
Implement the core functionality code
Below the header information, you can start writing the code for the plugin’s functionality. Let’s take a simple example: displaying a greeting message in the upper-left corner of the website’s footer. To avoid directly modifying the theme files, we will use WordPress’s hook system.
First of all, we need to create a function to output a greeting. Then, use it… add_action The function will hook this output to a certain execution action in WordPress, for example… wp_footer。
Recommended Reading Complete Guide to WordPress Plugin Development: From Zero to Live Deployment。
// 定义一个函数来输出问候语
function my_first_plugin_display_greeting() {
echo '<p style="position: fixed; bottom: 10px; left: 10px; background: #f1f1f1; padding: 10px; border-radius: 5px;">Hello, welcome to my website!</p>';
}
// 使用 add_action 钩子将函数挂载到 wp_footer 动作
add_action( 'wp_footer', 'my_first_plugin_display_greeting' ); After completing the above code, please move this plugin folder (for example,... my-first-pluginCopy the entire file to your WordPress installation directory. wp-content/plugins/ The plugin is already in the path. Next, log in to the WordPress administration panel and navigate to the “Plugins” menu. You should see the “Site Greeting” plugin there; click “Activate” to enable it. Now, visit the front end of your website, and you should see the custom greeting at the bottom of the page.
Add management options for the plugin
A fully functional plugin usually requires a configuration page that allows administrators to make settings in the WordPress backend. This involves creating a management menu and the logic for handling user inputs (options).
Create a plugin settings page.
WordPress provides functions for adding setup pages to plugins. Usually, we use these functions to… add_options_page Or add_menu_page Functions such as these are used to add this page to the background menu. The following example demonstrates how to add a simple settings sub-page under the “Settings” main menu.
First, create a function to render the HTML content for the settings page.
// 渲染插件设置页面的函数
function my_first_plugin_settings_page() {
?>
<div class="wrap">
<h1>Site Greeting Settings</h1>
<form method="post" action="/en/options.php/" data-trp-original-action="options.php">
<p><strong>Output:</strong>
</p>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
<?php
} Then, use add_action The hook is in admin_menu This is the “Stage Registration” page.
// 将设置页面添加到后台菜单
function my_first_plugin_add_admin_menu() {
add_options_page(
'问候语设置', // 页面标题
'站点问候语', // 菜单标题
'manage_options', // 权限要求
'my-first-plugin', // 菜单别名
'my_first_plugin_settings_page' // 渲染函数
);
}
add_action( 'admin_menu', 'my_first_plugin_add_admin_menu' ); Registration settings fields and data storage
Just having a page is not enough; we also need to define specific settings fields (such as input fields and dropdown menus) and handle the saving of data. This requires the use of the WordPress Settings API. register_setting、add_settings_section and add_settings_field Functions such as...
Recommended Reading From Zero to One: An Authoritative Guide and Practical Tutorial for WordPress Plugin Development。
The following code registers a settings group and a text field that allow users to customize the content of their greeting messages.
// 初始化插件的设置
function my_first_plugin_settings_init() {
// 注册一个设置,将其保存到 `options` 表的 `my_first_plugin_greeting_text` 字段中
register_setting( 'my_first_plugin_settings_group', 'my_first_plugin_greeting_text' );
// 在页面中添加一个设置区域
add_settings_section(
'my_first_plugin_section',
'自定义问候语',
null,
'my-first-plugin'
);
// 在设置区域中添加一个文本字段
add_settings_field(
'my_first_plugin_field',
'问候语文本',
'my_first_plugin_field_render',
'my-first-plugin',
'my_first_plugin_section'
);
}
add_action( 'admin_init', 'my_first_plugin_settings_init' );
// 渲染文本输入框的函数
function my_first_plugin_field_render() {
$option = get_option( 'my_first_plugin_greeting_text', '你好,欢迎来到我的网站!' );
echo '<input type="text" name="my_first_plugin_greeting_text" value="' . esc_attr( $option ) . '" style="width: 300px;" />';
} Finally, we need to modify the function that previously displayed the greeting message to read the user’s saved settings from the database.
function my_first_plugin_display_greeting() {
$greeting_text = get_option( 'my_first_plugin_greeting_text', '你好,欢迎来到我的网站!' );
echo '<p style="position: fixed; bottom: 10px; left: 10px; background: #f1f1f1; padding: 10px; border-radius: 5px;">'.\n' . esc_html( $greeting_text ) . '</p>';
} Plugin security and best practices
When developing plugins, security is the top priority. Insecure code can lead to website attacks. Here are some key security guidelines:
Data Validation and Cleanup
Anytime you retrieve data from user input (such as $_POST, $_GET) or from a database, you must assume that the data is untrusted. Before displaying it to the browser or saving it to the database, the data must be verified and cleaned.
For the content that is output to an HTML page, use esc_html()、esc_attr() Or wp_kses_post() Use functions such as escaping to prevent cross-site scripting attacks.
For variables used in database queries, it is advisable to use prepared statements or similar mechanisms. $wpdb->prepare() Such a method.
In our example, when saving the settings, WordPress… register_setting The function will automatically perform some basic cleaning tasks. When outputting the results, we used… esc_html() To ensure that the HTML tags in the greeting text are safely escaped and converted into plain text.
\nUsing non-CE and permission checks
When processing form submissions from the management page, it is essential to verify the legitimacy of the request. This includes checking the user's permissions and verifying a random number.
In the form on the settings page,settings_fields() The function already includes non-CE validation by default. However, if you create custom AJAX handlers or non-standard forms, you need to perform validation manually. This is commonly done using… current_user_can() Check the permissions and use them accordingly. check_admin_referer() Or wp_verify_nonce() Verify the random number.
For example, in a custom submission handler function:
function my_plugin_handle_form_submit() {
// 检查权限
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( '权限不足' );
}
// 验证随机数
if ( ! isset( $_POST['my_nonce_field'] ) || ! wp_verify_nonce( $_POST['my_nonce_field'], 'my_action' ) ) {
wp_die( '安全校验失败' );
}
// ... 处理安全的数据 ...
} summarize
By following this guide, you have completed the entire development process from a simple PHP file to a WordPress plugin with backend management capabilities. You have learned about the basic structure of plugins, how to use action hooks to add new functionality, how to utilize the WordPress Settings API to create configurable option pages, and the crucial importance of security practices. Remember: a great plugin is not only powerful but also requires clear, secure, and reliable code that adheres to WordPress’s coding standards. Starting with this small plugin, you can further explore more advanced features such as shortcodes, widgets, and custom post types, and gradually build more complex extensions.
FAQ Frequently Asked Questions
How to add multi-language support to a plugin?
Adding internationalization (i18n) support to a plugin mainly involves using text fields and translation functions. First, make sure that the necessary settings are correctly configured at the beginning of the plugin’s file. Text Domain and Domain PathIn the code, replace all strings that need to be translated with __() Or _e() Wrap the functions in appropriate functions (such as `add_filter()` or `add_action()`). Then, use tools like Poedit to create a POT (Poedit Translation Template) file, as well as the corresponding .mo (Machine Translation) and .po (Human Translation) files. Place these files in the language directory specified by the plugin.
For example:echo esc_html( __( ‘Hello, World!’, ‘my-first-plugin’ ) );When a user switches to the desired language, WordPress automatically loads the corresponding translation files.
How can function names in plugins be avoided from conflicting with those in other plugins?
The best practice for avoiding function name conflicts is to use namespaces (PHP 5.3+) or to add a unique prefix to all functions, classes, and constants. The prefix should be distinctive enough; commonly, an abbreviation or the full name of the plugin is used as the prefix.
For example, do not use… display_greeting()… instead of using my_first_plugin_display_greeting()If you use PHP namespaces, you can declare them at the top of the file. namespace MyFirstPlugin;Then, use short function names internally, and when making external calls, resolve them through the namespace.
How to publish a plugin to the official directory after its development is complete?
To publish a plugin to the official WordPress.org directory, you first need to create an account on WordPress.org and then submit your plugin there. The process involves the following steps: ensuring that your code complies with the GPL license, passing the PHPCS standard checks, preparing a readme.txt file (which follows a specific format), and providing clear screenshots and documentation. After submitting your plugin, reviewers will examine the code. If it passes the review, your plugin will be published. Once published, users will be able to search for and install your plugin directly from the WordPress administration panel.
How do plugins ensure backward compatibility with older versions of WordPress?
To maintain backward compatibility, it is essential to check the current version of WordPress during development and use conditional statements to wrap the code that relies on APIs from newer versions. Additionally, avoid using deprecated functions; if they must be used, make sure there are alternative solutions available. Clearly state the minimum version of WordPress required by the plugin in the plugin’s readme.txt file and provide clear instructions to users. Regularly testing the plugin’s functionality in older versions is crucial for maintaining compatibility.
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
- Why choose WooCommerce as your e-commerce solution?
- Becoming a WordPress Plugin Developer: A Complete Guide from Scratch
- WooCommerce Complete Guide: Building Your Online Store and Sales Strategy from Scratch
- Top 10 Essential WordPress Plugins to Enhance Website Performance and Security in Every Aspect