WordPress 插件开发基础教程
准备工作
- 本地开发环境(推荐 XAMPP/MAMP 或 Local by Flywheel)
- 文本编辑器(VS Code/Sublime/PhpStorm)
- 基础的 PHP/HTML 知识
- 测试用的 WordPress 网站
第一步:创建基础插件
1. 插件目录结构
在 wp-content/plugins/
下创建新目录:
my-first-plugin/
└── my-first-plugin.php
2. 添加插件头信息
在 my-first-plugin.php
中添加:
<?php
/**
* Plugin Name: My First Plugin
* Description: 这是我的第一个 WordPress 插件
* Version: 1.0.0
* Author: 你的名字
* Author URI: https://yourwebsite.com
*/
现在可以在 WordPress 后台插件列表看到这个插件并激活。
第二步:添加基础功能
1. 创建短代码(Shortcode)
// 添加短代码
add_shortcode('greeting', 'my_greeting_function');
function my_greeting_function($atts) {
$atts = shortcode_atts([
'name' => '访客'
], $atts);
return '<div class="greeting">你好,'.esc_html($atts['name']).'!</div>';
}
使用方式:在文章/页面中添加 [greeting name="小明"]
2. 添加管理菜单
add_action('admin_menu', 'my_plugin_menu');
function my_plugin_menu() {
add_menu_page(
'我的插件设置', // 页面标题
'我的插件', // 菜单名称
'manage_options', // 权限要求
'my-plugin-settings', // 菜单 slug
'settings_page', // 回调函数
'dashicons-smiley' // 图标
);
}
function settings_page() {
?>
<div class="wrap">
<h1>我的插件设置</h1>
<form method="post" action="options.php">
<?php
settings_fields('my_plugin_settings');
do_settings_sections('my-plugin-settings');
submit_button();
?>
</form>
</div>
<?php
}
第三步:添加设置选项
1. 注册设置
add_action('admin_init', 'register_plugin_settings');
function register_plugin_settings() {
register_setting('my_plugin_settings', 'my_plugin_options');
add_settings_section(
'main_section',
'主要设置',
'section_callback',
'my-plugin-settings'
);
add_settings_field(
'welcome_message',
'欢迎消息',
'welcome_message_callback',
'my-plugin-settings',
'main_section'
);
}
function section_callback() {
echo '<p>插件基础设置项</p>';
}
function welcome_message_callback() {
$options = get_option('my_plugin_options');
echo '<input type="text" name="my_plugin_options[welcome_message]"
value="'.esc_attr($options['welcome_message'] ?? '').'" class="regular-text">';
}
第四步:安全与最佳实践
1. 安全注意事项
- 所有输出使用
esc_html()
/esc_attr()
转义 - 使用 WordPress 的非ces字段(
wp_nonce_field()
) - 验证用户权限(
current_user_can()
)
2. 国际化支持
load_plugin_textdomain('my-plugin', false, dirname(plugin_basename(__FILE__)).'/languages/');
// 在需要翻译的字符串使用:
__('Hello World', 'my-plugin');
_e('Goodbye', 'my-plugin');
第五步:调试与发布
1. 调试技巧
- 在
wp-config.php
中启用: -
define('WP_DEBUG', true); define('WP_DEBUG_LOG', true);
- 使用
error_log()
记录日志 - 安装调试插件(Query Monitor, Debug Bar)
2. 打包发布
- 创建 README.txt
- 压缩为 zip 文件
- 可提交到 WordPress 官方插件目录
没有回复内容