WordPress’s plugin system is at the heart of its powerful extensibility. With plugins, developers can add a wide range of functionality to a website, ranging from simple contact forms to sophisticated e-commerce features. This article will guide you through the entire process of creating a fully functional plugin, helping you to understand its core structure, hook mechanisms, security considerations, and best practices. In the end, you will have a plugin that is ready to be published or used directly in your own projects.
Development environment and basic preparations
Before writing the first line of code, a stable and efficient development environment is of paramount importance. It not only allows you to focus on building the logic of your application but also helps to prevent many common errors.
Configuring the local development environment
It is recommended to use a local server environment suite, such as XAMPP, MAMP, or the more professional Local by Flywheel. Make sure your PHP version (version 7.4 or higher is recommended) is compatible with the WordPress environment you plan to deploy, and enable debugging mode. In WordPress,wp-config.phpIn the file, the settings are set up.WP_DEBUGFortrueThis will display all errors and warnings during the development phase, helping you to quickly identify and fix issues.
Recommended Reading Beginner's Guide to WordPress Plugin Development: From Zero Basics to Building Professional Functional Modules。
Plugin File Structure Planning
A standard plugin requires at least one main file. The common practice is to create a dedicated folder for the plugin, naming it after the plugin’s core functionality. For example…my-first-pluginIn this folder, the main file usually has the same name as the folder, with a file extension at the end..phpnamelymy-first-plugin.phpA clear structure makes it easier to add JavaScript, CSS, language packs, or class files later on.
Create the plugin main file and basic header information.
The “entry points” for plugins, as well as the identity verification process, both rely on the header information located at the top of the main file. This is crucial for WordPress to recognize and load the plugins correctly.
Write a standard plugin header.
At the beginning of the main PHP file, a specific PHP comment block must be used to provide plugin information. This information will be displayed on the “Plugins” management page in the WordPress administration area.
<?php
/**
* Plugin Name: 我的第一个功能插件
* Plugin URI: https://example.com/my-first-plugin
* Description: 这是一个实战指南中创建的示例插件,用于演示核心开发流程。
* Version: 1.0.0
* Author: 你的名字
* Author URI: https://example.com
* License: GPL v2 or later
* Text Domain: my-first-plugin
* Domain Path: /languages
*/ Among them,Plugin NameandText DomainThis field is mandatory; the other fields are optional. Text area.Text DomainUsed for internationalization support.
Prevent direct file access
To protect the security of the plugin code and prevent potential information leaks or errors that could arise from direct access to the main file via a URL, a direct access check needs to be added after the header information and before any other code.
Recommended Reading Guidelines for Custom Development of the WooCommerce Plugin: Building a Unique Online Store。
// 防止直接访问
if ( ! defined( 'ABSPATH' ) ) {
exit;
} constantABSPATHThis is the absolute path to the WordPress root directory, which is defined by WordPress during its execution. This condition ensures that the subsequent code will only be executed within a WordPress environment.
Implementing core functionality and using WordPress hooks
WordPress provides two powerful mechanisms: action hooks and filter hooks, which allow your code to intervene in the core process or modify data at specific moments. Understanding and utilizing these hooks is crucial for plugin development.
Use action hooks to add functionality.
Action hooks allow you to execute custom code when specific events occur. For example, we could create a feature that automatically adds copyright information at the bottom of an article’s content. This would require the use of action hooks.the_contentFilters (which are essentially filter hooks, but are used in a similar way to action hooks) and…wp_enqueue_scriptsAction hooks are used to load resources.
First of all, let's write a function.mfp_add_copyright_noticeAnd mount it to…the_contentOn the hook.
// 在文章内容后添加版权声明
function mfp_add_copyright_notice( $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;
}
add_filter( 'the_content', 'mfp_add_copyright_notice' ); The conditional check ensures that the copyright notice is only displayed in the main loop of a single article on the front end, and it does not affect the page layout, the article summary, or the backend functionality.
Using filter hooks to modify data
Filter hooks are used to modify any data that is passed to them. Suppose we want to modify certain parts of the website title; we can create a function and add it to the relevant system or process.wp_titleOr something more modern…document_title_partsFilters.
Recommended Reading Detailed Guide to the Entire WordPress Plugin Development Process: From Getting Started to Mastering the Skills。
// 修改网站标题后缀
function mfp_modify_title_suffix( $title ) {
if ( is_home() ) {
$title['suffix'] = ' | 我的精彩博客';
}
return $title;
}
add_filter( 'document_title_parts', 'mfp_modify_title_suffix' ); Introducing scripts and styles securely
In order to add front-end styles or interactions to a plugin, it is necessary to use the methods recommended by WordPress.wp_enqueue_style()andwp_enqueue_script()The function, and throughwp_enqueue_scriptsHook call.
// 注册并排队插件的前端样式
function mfp_enqueue_frontend_assets() {
// 获取插件目录的URL
$plugin_url = plugin_dir_url( __FILE__ );
// 排队一个CSS文件
wp_enqueue_style(
'mfp-frontend-style',
$plugin_url . 'assets/css/frontend.css',
array(),
'1.0.0'
);
// 排队一个JS文件,并依赖jQuery
wp_enqueue_script(
'mfp-frontend-script',
$plugin_url . 'assets/js/frontend.js',
array( 'jquery' ),
'1.0.0',
true // 在页脚加载
);
}
add_action( 'wp_enqueue_scripts', 'mfp_enqueue_frontend_assets' ); Create a management page and set options.
Many plugins require the provision of configuration options for users. WordPress offers a settings API that allows for the creation of management menus and option pages in a secure and standardized manner.
Add a management menu
First, useadd_action( ‘admin_menu’, … )Come and register a new management menu item or sub-menu item. The function below is used for this purpose.mfp_create_admin_menuA sub-menu page will be added under the “Settings” main menu.
// 创建插件管理菜单
function mfp_create_admin_menu() {
add_options_page(
‘我的插件设置’, // 页面标题
‘我的插件’, // 菜单标题
‘manage_options’, // 权限要求
‘mfp-settings’, // 菜单slug
‘mfp_settings_page_html’ // 用于输出页面内容的回调函数
);
}
add_action( ‘admin_menu’, ‘mfp_create_admin_menu’ ); Build a settings page and its fields.
Next, it is necessary to define the callback function.mfp_settings_page_htmlThis code is used to render the page content, and it also registers a settings group, an option, and specific fields using the provided API.
// 设置页面的HTML输出
function mfp_settings_page_html() {
// 检查用户权限
if ( ! current_user_can( ‘manage_options’ ) ) {
return;
}
?>
<div class="“wrap”">
<h1></h1>
<form action="/en/“options.php”/" method="“post”" data-trp-original-action="“options.php”">
<?php
// 输出设置字段、非ce等
settings_fields( ‘mfp_options_group’ );
do_settings_sections( ‘mfp-settings’ );
submit_button( ‘保存设置’ );
?>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
‘mfp_field_copyright_text’ )
);
}
add_action( ‘admin_init’, ‘mfp_settings_init’ );
// 渲染版权文本文档字段
function mfp_field_copyright_text_html() {
$options = get_option( ‘mfp_options’ );
$value = $options[‘copyright_text’] ?? ‘默认版权文本’; // PHP 7.0+ 空合并运算符
?>
<input type="“text”"
id="“mfp_field_copyright_text”"
name="“mfp_options[copyright_text]”"
value="“NO NUMERIC NOISE KEY" 1000”
class="“regular-text”">
<?php
} Now, you can use what you have done before…mfp_add_copyright_noticeIn the function, we useget_option( ‘mfp_options’ )[‘copyright_text’]Dynamically retrieve the backend text based on the user's settings to make the plugin functionality configurable.
summarize
This article provides a detailed overview of the entire process of developing a WordPress plugin from scratch. We start by setting up the development environment and creating the main file that includes the standard header information, emphasizing the importance of security measures. Next, we delve into the core of WordPress plugin development: the hook system. We explain how to use action hooks to execute code and filter hooks to modify data, and demonstrate methods for securely loading front-end resources. Finally, we use the WordPress Settings API to create a professional-looking administration page that allows users to customize the plugin’s functionality.
The entire development process adhered to WordPress coding standards and best practices, including the use of unique function prefixes, data validation and escaping, as well as the foundation for providing internationalization support. Once you have mastered these basic concepts, you can infinitely expand the functionality of your plugin by combining different hooks, creating custom database tables, developing plugins or shortcodes.
FAQ Frequently Asked Questions
How to choose appropriate prefixes for plugin functions and classes?
All global functions, classes, variables, and constants within a plugin should use a unique prefix to prevent naming conflicts with other plugins or themes. The prefix is typically derived from the plugin’s name or an abbreviation of it. For example, if the plugin is named “My First Plugin,” a suitable prefix could be “MFP-”.mfp_Ormyfirstplugin_It is of utmost importance to maintain consistency.
Why is it necessary to use `wp_enqueue_script` to add scripts?
utilizationwp_enqueue_script()andwp_enqueue_style()This is a method officially recommended by WordPress. It ensures that script dependencies (such as jQuery) are properly handled, prevents the same script from being loaded multiple times, and allows other plugins or themes to function correctly.wp_deregister_script()Come and safely remove or replace your script. Just use it directly.If tags are inserted, these management benefits will not be available, and conflicts may occur.
What are some important security guidelines when developing plugins?
The primary principle is: Never trust user input. For everything that comes from users…$_GET、$_POST、$_REQUESTThe data obtained from the database may need to be verified, cleaned, and escaped before being used in HTML.esc_html()、esc_attr(); Output for use in URLsesc_url()In SQL queries, it is essential to use…$wpdb->prepare()Perform parameterized queries to prevent SQL injection. At the same time, use…current_user_can()Check the user's permissions.
How can I add internationalization support to my plugin?
First of all, make sure to set the correct values in the plugin header information.Text DomainandDomain PathThen, in the code, replace all the strings that need to be translated with the appropriate translations.()Please provide the text you would like to have translated._e()Perform echo translation, for example.( ‘Hello World’, ‘my-first-plugin’ )Finally, use a tool like Poedit to scan the code and generate the necessary content..potTemplate files, and create them for different languages..poand.moTranslate the file and place it in…/languagesUnder the directory.
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.
- Why Choose WordPress: The Top Ten Core Advantages of an Open-Source CMS
- Master WooCommerce in Ten Minutes: A Guide to Building an E-commerce Website from Scratch to Profit
- WooCommerce Complete Guide: An Advanced E-commerce Configuration Tutorial from Installation to Live Deployment
- What is WordPress? A comprehensive introduction to a content management system
- Preface: Why choose WordPress for development?