Why start learning WordPress development by working with plugins?
One of the core design philosophies of WordPress is its high level of extensibility, and plugins are the primary means of achieving this feature. This is in contrast to directly modifying the theme itself.functions.phpCompared to creating individual files, creating a separate plugin offers significant advantages. A plugin separates the functional logic from the appearance of the website theme, ensuring that the core functionality is retained when you change the theme. This makes the code more organized and easier to maintain, facilitating code reuse, version control, and sharing with other developers.
From a technical perspective, a plugin is essentially one or more PHP files that adhere to specific WordPress standards and are placed in a designated location within the WordPress framework./wp-content/plugins/The files are located in this directory. When WordPress is initialized, it scans this directory and loads the code of all active plugins. This means that you can modify or enhance almost any aspect of WordPress almost without limitations using plugins—everything from adding a simple shortcode to creating a complex management panel.
Build your first plug-in infrastructure
The first step in creating a WordPress plugin is to establish its basic file structure. Although a plugin can consist of only one file, a well-structured organization will make it easier to maintain in the long run.
Recommended Reading A Beginner's Guide to WordPress Plugin Development: Building Your First Custom Function Extension from Scratch。
Create the main plug-in file
Each plugin must have a main file that contains the plugin’s metadata. We start by working on this in the local development environment./wp-content/plugins/Create a new folder under the directory, for examplemy-first-pluginThen, create the main PHP file inside that folder; it usually has the same name as the folder.my-first-plugin.php。
At the beginning of this main file, we need to add a standard plugin information comment block. This comment block is crucial for WordPress to recognize the plugin and display it in the administration panel.
<?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
*/ Define the core class of the plugin.
To maintain the encapsulation of the code and avoid naming conflicts, the best practice is to use object-oriented programming (OOP) by encapsulating all the functionality of the plugin within a single class. We define this class in the main file.
if ( ! class_exists( 'My_First_Plugin' ) ) {
class My_First_Plugin {
/**
* 构造方法,用于初始化插件
*/
public function __construct() {
// 初始化钩子
$this->init_hooks();
}
/**
* 初始化WordPress动作和过滤器钩子
*/
private function init_hooks() {
// 钩子将在这里添加
}
}
// 实例化插件类
new My_First_Plugin();
} if ( ! class_exists( 'My_First_Plugin' ) )It is a security check to prevent classes from being defined repeatedly.__construct()This is the constructor of the class, which is automatically invoked when the class is instantiated. We called a private method within it.init_hooks()This is for centralized management of the registration of all hooks.
Using the hook system to add functionality
WordPress’s Hook system is the core of its event-driven architecture, consisting of Actions and Filters. Actions allow you to execute code at specific moments, while Filters enable you to modify data.
Recommended Reading From Beginner to Expert in WordPress Plugin Development: A Step-by-Step Guide to Creating Custom Features。
Add custom copyright information to the article content.
A common requirement is to automatically add copyright information at the end of each article. This can be achieved by…the_contentThis is achieved using filters. We…init_hooks()Add this filter to the method.
First of all, update it.init_hooks()Method:
private function init_hooks() {
// 使用过滤器在文章内容后追加版权信息
add_filter( 'the_content', array( $this, 'append_copyright_notice' ) );
} Here,add_filter()The function is from our class.append_copyright_noticeThe method is mounted to…the_contentIt’s on the filter. Now, we need to define this callback method.
/**
* 在文章内容后追加版权信息的回调函数
*
* @param string $content 原始文章内容。
* @return string 追加了版权信息后的内容。
*/
public function append_copyright_notice( $content ) {
// 仅在主查询的单篇文章页面显示
if ( is_single() && in_the_loop() && is_main_query() ) {
$copyright_text = sprintf(
'<p><small>Copyright Notice: This article was originally published on %s. Please cite the source when reproducing it.</small></p>',
get_bloginfo( 'name' )
);
$content .= $copyright_text;
}
return $content;
} This method receives the original data.$contentThrough conditional judgmentis_single()、in_the_loop()andis_main_query()We ensure that copyright information only appears in the main content of the single article page on the front end, without affecting the page layout, the article summary, or the administration backend. Next, we create the copyright text and use string concatenation operators to assemble it..=Attach it to the original content, and then return the modified content.
Create a management menu page.
Adding a simple settings page for a plugin is another common feature. This requires the use of action hooks. We will create a top-level administration menu page.
Ininit_hooks()Add another action to the sequence:
Recommended Reading WordPress Plugin Development Beginner's Guide: Creating Your First Functional Module from Scratch。
private function init_hooks() {
add_filter( 'the_content', array( $this, 'append_copyright_notice' ) );
// 添加管理菜单
add_action( 'admin_menu', array( $this, 'add_admin_menu_page' ) );
} When WordPress generates its administration menu, a certain process is triggered.admin_menuActions. Let's define them next.add_admin_menu_page()Method.
/**
* 向WordPress管理后台添加一个自定义菜单页面
*/
public function add_admin_menu_page() {
add_menu_page(
'我的第一个插件', // 页面标题
'我的插件', // 菜单标题
'manage_options', // 权限要求
'my-first-plugin-page', // 菜单别名
array( $this, 'render_admin_page' ), // 回调函数,用于输出页面内容
'dashicons-admin-plugins', // 图标
80 // 菜单位置
);
} add_menu_page()The function is part of the WordPress core API and is used to register a top-level menu.manage_optionsThis is a permission identifier, which means that only administrators can see this menu. We have specified the relevant settings accordingly.render_admin_pageMethods for rendering page content.
/**
* 渲染管理页面内容的回调函数
*/
public function render_admin_page() {
?>
<div class="wrap">
<h1>My first plugin management page</h1>
<p>Congratulations! You have successfully created a WordPress plugin that includes a management page.</p>
<p>This is a simple example page where you can add forms, set options, and more.</p>
<p>The current site name is:<strong><?php echo esc_html( get_bloginfo( 'name' ) ); ?></strong></p>
</div>
<?php
} Implementing best practices for internationalization and security
A standard plugin should take into account internationalization and security to ensure that it can be used safely by users around the world.
Make the plugin support multiple languages.
Internationalization (i18n) allows the plugin text to be translated. We have already specified this in the comments at the beginning of the plugin.Text Domain: my-first-pluginNow it is necessary to use…__()Or_e()A function is used to wrap all the output strings.
Firstly, in__construct()Orinit_hooks()Add an action to load the translation files:
add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) ); Define a method for loading translations:
public function load_textdomain() {
load_plugin_textdomain(
'my-first-plugin',
false,
dirname( plugin_basename( __FILE__ ) ) . '/languages/'
);
} Then, modify the sections where the previously generated text was displayed. For example, update the relevant content.append_copyright_noticeThe text within the method:
$copyright_text = sprintf('<p><small>© %s: %s, %s.</small></p>',
__( '版权声明', 'my-first-plugin' ),
sprintf( __( '本文首发于%s', 'my-first-plugin' ), get_bloginfo( 'name' ) ),
__( '转载请注明出处', 'my-first-plugin' )
); Similarly, update the strings on the update management page:
<h1><?php esc_html_e( '我的第一个插件管理页面', 'my-first-plugin' ); ?></h1>
<p><?php esc_html_e( '恭喜!你已经成功创建了一个带有管理页面的WordPress插件。', 'my-first-plugin' ); ?></p> esc_html_e()The function not only outputs the translated text but also performs HTML escaping, thereby enhancing security.
Escape Output and Verify Input
In plugin development, all data that is sent to the front-end or browser must be escaped, and all input from users or external sources must be validated and cleaned.
When displaying the site names, we have already used the appropriate format.esc_html()These are the key steps to prevent Cross-Site Scripting (XSS) attacks. If a function name ends with “_e” (which stands for “echo”), it will usually output the content after it has been escaped directly. Functions that start with “__” on the other hand, return the translated string, and you need to manually escape the content before outputting it.
If our management page is going to handle form submissions in the future, we must use…wp_verify_nonce()To validate the request and use it…sanitize_text_field()、intval()Use functions to clean the data entered by users before storing it in the database or performing any other operations. This is an essential step in protecting the security of a website.
summarize
Following this guide, we started by creating a basic plugin file structure and gradually implemented the core functionality of the plugin. We learned how to organize code using an object-oriented approach, how to utilize WordPress’s powerful action and filter hooks to intervene in its execution process, how to add custom functionality to article content, and how to create a management backend page. Additionally, we discussed two crucial aspects of professional plugin development: internationalization (i18n) and secure output/input.
This is just the starting point. Based on this framework, you can explore even more possibilities: adding settings options, creating custom article types and taxonomies, writing widgets, implementing AJAX interactions, handling shortcodes, and so on. Remember that reading the official WordPress plugin documentation and the core code is the best way to gain a deeper understanding of the system. Now that you have mastered the basic skills needed to build WordPress plugins from scratch, you can start turning your ideas into reality.
FAQ Frequently Asked Questions
Do plugins have to be developed using classes?
Not necessarily. WordPress plugins can be written using purely procedural functions. However, it is more recommended to use classes (object-oriented programming) because it allows for better organization of the code. Classes encapsulate variables and methods within separate namespaces, which effectively prevents conflicts with function names in other plugins or themes, and enhances the maintainability and reusability of the code.
How do I debug my plugin?
A common debugging method in WordPress development is to enable WP_DEBUG. This can be done by adding the following line to the `wp-config.php` file, located in the root directory of your website:wp-config.phpIn the file, find and modify the following line:define( 'WP_DEBUG', true );You can also set it up at the same timedefine( 'WP_DEBUG_LOG', true );In this way, the error messages will be recorded./wp-content/debug.logThe file content is not displayed on the page. Additionally, using the Console and Network tabs in the browser’s developer tools, as well as the PHP error logs, are all effective methods for identifying and resolving issues.
Can I use jQuery directly in the plugin?
Yes, that’s possible. The WordPress core already includes the jQuery library. To properly and securely incorporate your custom JavaScript files or dependencies, you should use…wp_enqueue_script()The function is declared, and it is also listed in the dependency array.array( 'jquery' )In this way, WordPress will ensure that jQuery is loaded before your script. Never hard-code a remote jQuery CDN link directly into a plugin, as this can lead to conflicts or security issues.
What checks need to be done before releasing a plugin?
Before releasing the plugin, it is recommended to conduct the following checks: ensure that the code complies with WordPress coding standards; complete internationalization preparations, ensuring that all user-visible strings have been wrapped with translation functions; conduct compatibility tests on multiple WordPress and PHP versions; check whether all output has been properly escaped, and whether all input has been properly validated and cleaned; provide a clear uninstallation method that can delete all database options and tables created by the plugin (if necessary); and write detailed documentation.readme.txtFiles. These steps can enhance the professionalism and reliability of 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