
您现在的位置是:首页 > WordPress教程WordPress教程
WordPress自定义插件开发
WP集市
2025-09-10
【WordPress教程】
759人已围观
-
先唠唠为啥要自己写插件。WordPress本身是个毛坯房,主题是装修风格,插件就是家具电器——但现成插件可能太笨重或者不符合你的奇葩需求。比如你想在文章底部自动加上“本文作者真帅”,总不能手动每篇粘贴吧?这时候自己搓个插件最划算。
-
创建插件基本操作:在wp-content/plugins里新建个文件夹,比如叫my-awesome-plugin,里面必须有个同名PHP文件。文件开头写注释声明,这是插件的身份证:
<?php
/**
* Plugin Name: 超级无敌插件
* Description: 用来证明作者很帅的插件
* Version: 1.0
* Author: 你本人
*/
- 核心套路就是用钩子(Hooks)。WordPress整个系统就像个挂满钩子的墙,你的代码就是挂在上面的衣服。比如用
add_filter
给文章内容挂个过滤器:
function add_handsome_message($content) {
if (is_single()) {
$content .= "<p style='color:red'>本文作者真帅</p>";
}
return $content;
}
add_filter('the_content', 'add_handsome_message');
- 再来个实战案例:自定义短代码(Shortcode)。比如做个能显示当前时间的短码
[show_time]
,用户在文章里插入这个就能显示动态时间:
function current_time_shortcode() {
return date('Y年m月d日 H:i:s');
}
add_shortcode('show_time', 'current_time_shortcode');
- 保存数据得用WordPress选项API。比如做个设置页面让用户自定义炫耀文字:
function handsome_menu() {
add_options_page(
'帅气设置',
'帅气设置',
'manage_options',
'handsome-settings',
'handsome_settings_page'
);
}
add_action('admin_menu', 'handsome_menu');
function handsome_settings_page() {
?>
<div class="97b8-0a8c-d942-fdaa wrap">
<h2>炫耀词设置</h2>
<form method="post" action="options.php">
<?php settings_fields('handsome-settings-group'); ?>
<input type="text" name="handsome_text" value="<?php echo get_option('handsome_text'); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
- 记得要注册设置项和验证数据,WordPress不会自动帮你擦屁股:
function register_handsome_settings() {
register_setting(
'handsome-settings-group',
'handsome_text',
'sanitize_text_field'
);
}
add_action('admin_init', 'register_handsome_settings');
- 最后把之前写死的炫耀文字改成动态的:
function add_handsome_message($content) {
if (is_single()) {
$text = get_option('handsome_text', '本文作者真帅'); // 第二个参数是默认值
$content .= "<p style='color:red'>" . esc_html($text) . "</p>";
}
return $content;
}
-
安全提醒三连:永远不要相信用户输入的数据,用
esc_html()
、sanitize_text_field()
这些函数过滤输出和输入,非管理员权限检查用current_user_can('manage_options')
。 -
调试技巧:打开WP_DEBUG,看错误日志。有时候代码没生效不是因为玄学,是因为你拼错函数名——比如把
add_shortcode
写成add_shortcode
(注意第二个多打了个e),这种鬼畜错误只有日志能救你。 -
插件发布前记得写卸载钩子,不然用户删插件时残留数据在数据库里很尴尬:
function handsome_uninstall() {
delete_option('handsome_text');
}
register_uninstall_hook(__FILE__, 'handsome_uninstall');
总之自己写插件就像给WordPress造乐高零件,用钩子挂载功能,用选项存数据,注意安全性和清理现场。从一个小功能开始试水,慢慢就能组装出专属的瑞士军刀。
Tags:
文章版权声明:除非注明,否则均为WP集市原创文章,转载或复制请以超链接形式并注明出处。
上一篇:WordPress自定义函数编写
下一篇:WordPress自定义字段添加

热门文章
