08 插件结构与模块化
整理插件头、目录结构、加载文件、激活停用、卸载和类封装。
首页
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
本页关键词
plugin header
activation hook
deactivation hook
uninstall.php
classes
学习目标
会写最小插件
会拆分 include 文件
知道激活/停用/卸载区别
理解类封装插件入口
代码使用提醒
本页代码适合用于学习和研究。复制到正式网站前,请先备份,并优先在测试环境验证。
涉及用户输入、后台保存、接口请求、删除操作和邮件发送时,要同时考虑权限、nonce、sanitize、validate 和 escape。
1. 最小插件文件
基础
<?php
/**
* Plugin Name: My Site Toolkit
* Description: 网站自定义功能集合。
* Version: 1.0.0
* Author: Your Name
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'init', 'mysite_toolkit_init' );
function mysite_toolkit_init() {
// 插件功能入口。
}
插件头注释决定后台插件列表显示。
2. 推荐插件目录结构
结构
my-site-toolkit/
├── my-site-toolkit.php
├── includes/
│ ├── helpers.php
│ ├── shortcodes.php
│ └── admin.php
├── assets/
│ ├── css/
│ └── js/
└── uninstall.php
代码多了以后要拆分文件,不要全部塞进一个 PHP。
3. 加载 includes 文件
基础
<?php
define( 'MYSITE_TOOLKIT_PATH', plugin_dir_path( __FILE__ ) );
define( 'MYSITE_TOOLKIT_URL', plugin_dir_url( __FILE__ ) );
require_once MYSITE_TOOLKIT_PATH . 'includes/helpers.php';
require_once MYSITE_TOOLKIT_PATH . 'includes/shortcodes.php';
require_once MYSITE_TOOLKIT_PATH . 'includes/admin.php';
定义 PATH 和 URL 常量能让文件引用更清晰。
4. 激活和停用 hook
维护
<?php
function mysite_toolkit_activate() {
// 创建默认选项、刷新 rewrite 等。
update_option( 'mysite_toolkit_version', '1.0.0' );
}
register_activation_hook( __FILE__, 'mysite_toolkit_activate' );
function mysite_toolkit_deactivate() {
// 停用时清理临时计划任务等。
}
register_deactivation_hook( __FILE__, 'mysite_toolkit_deactivate' );
激活不是每次加载,停用也不是卸载。
5. uninstall.php 清理数据
维护
<?php
// uninstall.php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
delete_option( 'mysite_toolkit_version' );
delete_option( 'mysite_phone' );
只有用户删除插件时才会执行 uninstall.php。
6. 类封装插件入口
进阶
<?php
final class MySite_Toolkit {
public function __construct() {
add_action( 'init', array( $this, 'init' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'assets' ) );
}
public function init() {
// 初始化功能。
}
public function assets() {
// 加载资源。
}
}
new MySite_Toolkit();
类封装适合中大型插件,能减少全局函数冲突。
本页总结
插件学习的重点不是把代码都放一起,而是理解生命周期、目录结构和模块化。这样后期扩展才不乱。