WordPress Plugin Development Environment and Basic Preparation
Before starting to write code, a stable and efficient development environment is of paramount importance. This not only improves your development efficiency but also helps you follow best practices, ensuring the quality and compatibility of your plugins.
First of all, you need a local WordPress development environment. You can set it up quickly using tools such as XAMPP, MAMP, Local by Flywheel, or Docker. Make sure that your environment is running a relatively recent version of PHP (version 7.4 or higher is recommended) as well as MySQL/MariaDB. A local development environment allows you to test and debug your code freely without affecting your live website.
Secondly, you need a code editor or an integrated development environment (IDE). Tools like Visual Studio Code, PhpStorm, or Sublime Text are all excellent choices, as they offer features such as syntax highlighting, code suggestions, and debugging capabilities. It is also recommended to install code quality tools, such as PHP_CodeSniffer, and to configure the WordPress coding standards to ensure that your code style is consistent with the WordPress core.
Recommended Reading Complete Guide to WordPress Plugin Development: From Getting Started to Building Professional-Level Extensions。
Finally, understanding the basic structure of WordPress plugins is the first step. The simplest plugin only requires a main PHP file, which should contain specific plugin information comments at the beginning of the file. This file serves as the entry point for the plugin, and WordPress uses this information to identify and manage it.
Create your first plug-in file
Let’s start by creating the simplest “Hello World” plugin. This process will help you understand the basic framework of plugins and how WordPress recognizes them.
First, in the WordPress installation directory, you need to create a new folder called "wp-content/uploads".wp-content/pluginsInside the folder, create a new sub-folder. The name of the sub-folder should be unique, descriptive, and should consist of lowercase letters and hyphens (–), for example:my-first-plugin。
Inside this folder, create a main PHP file. The name of the file should usually be the same as the name of the folder, for example:my-first-plugin.phpAt the top of this file, you must add a plugin header comment that complies with WordPress standards. This comment serves as the “identification” for your plugin, containing information such as the name, description, version, and author. Without this comment, WordPress will not be able to find your plugin in the background plugin list.
The following is an example of the most basic plugin file:
Recommended Reading Starting from scratch: Why choose WordPress plugin development?。
<?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
*/
// 防止直接访问文件
if ( ! defined( 'ABSPATH' ) ) {
exit; // 如果ABSPATH未定义,则退出
} After saving this file, log in to your WordPress administration panel and go to the “Plugins” page. You should see “My First Plugin” listed in the plugin directory. At this point, you can activate it, but it won’t perform any functionality yet. The code in the file…if ( ! defined( ‘ABSPATH’ ) )Checking is an important security practice that prevents users from directly accessing your plugin files via a URL, ensuring that the code is only executed within the WordPress environment.
Add core functionality to the plugin.
An activated plugin needs to perform certain operations. In WordPress, this is mainly achieved through “Action Hooks” and “Filter Hooks.” These are the cornerstone of the WordPress plugin architecture, allowing you to insert your own code or modify data at specific points in the program’s execution.
Using action hooks to add notifications to the administration panel
Action hooks allow you to execute your own functions at specific moments during the WordPress process (for example, after initialization, when the page header is loaded, or when an article is saved). Let’s add a simple feature: displaying a welcome message at the top of the WordPress administration panel.
We will useadmin_noticesThis action hook: First, you need to create a function that generates the HTML content, and then use it…add_action()The function “mounts” this other function onto the hook.
In your main plugin file, add the following code:
/**
* 在管理后台显示欢迎通知
*/
function myfp_display_admin_notice() {
?>
<div class="notice notice-success is-dismissible">
<p>Welcome to use “My First Plugin”! The plugin has been successfully activated.</p>
</div>
<?php
}
// 将函数挂载到 admin_notices 动作钩子
add_action( 'admin_notices', 'myfp_display_admin_notice' ); Save and refresh your WordPress backend. You should see a green success message box at the top of the page. Note the function name.myfp_display_admin_noticeThe prefix was used.myfp_(This is taken from the abbreviation of the plugin name; it is used to avoid conflicts with function names of other plugins or themes. This is a naming convention that must be followed.)
Recommended Reading WordPress Plugin Development Guide: Building High-Quality WordPress Extensions from Scratch。
Use the filter hook to modify the content of an article.
Filter hooks allow you to modify the data that is passed through in WordPress. For example, you can change the appearance of an article’s content, title, or summary before it is displayed. Let’s create a function that automatically adds a copyright statement at the end of each article.
We will usethe_contentThis filter hook requires you to create a function that receives the original content.$contentModify the function for that, and then return the modified content.
Add the following code to your plugin file:
/**
* 在文章内容末尾添加版权声明
* @param string $content 原始的文章内容
* @return string 修改后的文章内容
*/
function myfp_add_copyright_to_content( $content ) {
// 仅对主循环中的单篇文章页面生效
if ( is_single() && in_the_loop() && is_main_query() ) {
$copyright_text = '<p><em>The copyright of this article belongs to this website. Please indicate the source when reposting it.</em></p>';
$content .= $copyright_text;
}
return $content;
}
// 将函数挂载到 the_content 过滤器钩子,优先级为10
add_filter( 'the_content', 'myfp_add_copyright_to_content', 10 ); Now, whenever you view any article on the website, the copyright notice you added will appear at the bottom of the content. The conditional statements in the function are responsible for this behavior.is_single() && in_the_loop() && is_main_query()This is very important; it ensures that this text will only be displayed within the main loop of the individual article pages on the frontend, and not in the home page list, widgets, or other areas. This is a detail that needs to be taken into consideration when developing high-quality plugins.
Plugin Internationalization and Best Practices
In order for your plugin to be used by users around the world, internationalization (i18n) is an essential step. WordPress provides a complete set of functions to support the translation of text within the plugin into other languages.
Prepare the plugin text to support translation.
You need to use a specific function to wrap all the strings that are displayed to the user within the plugin. The most commonly used function is…()Used to obtain the translation._e()Used for directly displaying the translated text, as well as…esc_html()Used in contexts where HTML needs to be escaped.
First of all, modify the text in the notification function and the copyright function that we created earlier by using the translation function:
function myfp_display_admin_notice() {
?>
<div class="notice notice-success is-dismissible">
<p><?php _e( '欢迎使用“我的第一个插件”!插件已成功激活。', 'my-first-plugin' ); ?></p>
</div>
<?php
}
function myfp_add_copyright_to_content( $content ) {
if ( is_single() && in_the_loop() && is_main_query() ) {
$copyright_text = '<p><em>' . esc_html__( '本文版权归本网站所有,转载请注明出处。', 'my-first-plugin' ) . '</em></p>';
$content .= $copyright_text;
}
return $content;
} Note that each translation function includes a second parameter.‘my-first-plugin’This is what you defined at the top of the plugin.Text DomainIt is a unique identifier that tells WordPress to which plugin these strings belong.
Then, you need to specify it in the comments at the top of the plugin.Domain PathThat is to say…/languagesPlace the translation files (.po and .mo files) in the specified folder. You can use tools such as Poedit to create and manage these translation files.
Comply with security and coding standards.
Security is of utmost importance in plugin development. Never trust the data provided by users. Always be cautious when processing any information coming from users.$_GET、$_POSTOr$_REQUESTThe data must be validated, cleaned, and escaped before being used.
WordPress offers a wealth of functions to assist you:
* 验证(Validation):检查数据是否符合预期格式(如is_email())。
* 清理(Sanitization):清除数据中的非法字符(如sanitize_text_field(), sanitize_email())。
* 转义(Escaping):在将数据输出到HTML、JavaScript或URL之前,确保其安全(如esc_html(), esc_js(), esc_url())。
In addition, when directly operating on the database, be sure to use the WordPress database classes.$wpdbThe methods provided, such as…$wpdb->prepare()This is to prevent SQL injection attacks.
summarize
By following this guide, you have completed the entire process of creating a fully functional WordPress plugin from scratch. You have learned how to set up the development environment, create the basic plugin files, use action and filter hooks to add new features to WordPress, and how to enhance the professionalism and usability of your plugin through internationalization and security practices. The core of plugin development lies in understanding and making proficient use of WordPress’s hook system, which offers unparalleled scalability and flexibility. Remember to start with simple features, iterate gradually, and always prioritize security and code quality. By doing so, you can create powerful and reliable WordPress plugins.
FAQ Frequently Asked Questions
Does a plugin have to be placed in a folder?
Not necessarily. A very simple, single-file plugin can directly do that.plugin-name.phpPut it there.wp-content/plugins/The files are located in the directory. However, for any plugin that contains multiple files (such as CSS, JS, images, or language files), it is highly recommended to use a separate folder to organize all the related files. This will make the structure clearer and easier to manage.
How to create a settings page for my plugin?
You can use the settings API provided by WordPress to create professional and secure setup pages. The main steps include: usingadd_menu_page()Oradd_submenu_page()The function registers a menu page and then uses it.register_setting()、add_settings_section()andadd_settings_field()Use functions to define the settings fields and chapters. Finally, write a callback function to generate the HTML form for the settings page.
Why are prefixes so important in plugin development?
WordPress is a vast ecosystem composed of plugins and themes. All the code runs within the same global namespace. If you define a variable named…get_data()If a common function is defined in the main code, and another plugin also defines a function with the same name, it can lead to a fatal error that causes the website to crash. Using a unique prefix (such as an abbreviation of the plugin name) can greatly reduce the likelihood of such conflicts and ensure the compatibility of the plugins.
How should I debug my plugin code?
In WordPress development, the preferred tool for debugging is to enable…WP_DEBUGYou can do that on the website.wp-config.phpIn the file, this is achieved by making certain settings.define( ‘WP_DEBUG’, true );Enable it. This will cause all PHP errors, warnings, and notifications to be displayed on the screen. For more advanced debugging, you can use…error_log()The function writes the information to the server’s error log, or you can use professional PHP debugging tools such as Xdebug in conjunction with your IDE for line-by-line debugging.
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.
- How to choose and customize the perfect WordPress theme for you
- WordPress Plugin Development Guide: Creating Your First Custom Plugin from Scratch
- Becoming a WordPress Plugin Developer: A Complete Guide from Scratch
- From Zero to One: A Comprehensive Guide and Practical Tips for Building Professional Websites with WordPress
- WordPress Plugin Development Complete Guide: From Beginner to Expert – Creating Professional Extensions