WordPress插件开发
入门
1、 进入 wp-content 目录
2、 进入plugins目录
3、 创建一个自己插件的新目录 比如 plugin-my 并进入
4、 创建一个新的php文件
注意: 这个php文件的头注释 是有一定格式的 且不能少
wordpress钩子有两种: 操作和过滤 允许你添加和更改WordPress功能
创建插件的3个基本钩子:
- register_activation_hook()
- register_deactivation_hook()
- register_uninstall_hook()
wp-include/load.php 部门可用的函数检测 比如 is_network_admin
添加钩子
使用 do_action
添加自定义钩子
卸载钩子
使用 remove_action
卸载钩子 注意优先级
头部注释要求
最小要求:
<?php
/*
* Plugin Name: YOUR PLUGIN NAME
*/
?>
头注释字段说明:
- Plugin Name:(必需的)你的插件,它会显示在WordPress管理的插件列表的名称。
- Plugin URI:插件的主页,应该是唯一的URL,最好在您自己的网站上。这对于您的插件必须是唯一的。您不能在此处使用WordPress.org URL。
- Description:插件的简短描述,如WordPress Admin的“插件”部分中所示。将此说明的字符数少于140个。
- Version:插件的当前版本号,例如1.0或1.0.3。
- Requires at least:该插件可以使用的最低WordPress版本。
- Requires PHP :所需的最低PHP版本。
- Author:插件作者的名称。可能使用逗号列出多个作者。
- Author URI :作者的网站或其他网站上的个人资料,例如WordPress.org。
- License:插件许可证(例如GPLv2)的简称。有关许可的更多信息,请参见WordPress.org指南。
- License URI:指向许可证全文的链接(例如https://www.gnu.org/licenses/gpl-2.0.html)。
- Text Domain:插件的gettext文本域。有关更多信息,请参见如何国际化插件页面的“ 文本域”部分。
- Domain Path:域路径使WordPress知道在哪里可以找到翻译。有关更多信息,请参见“ 如何国际化插件”页面的“ 域路径”部分。
- Network:插件是否只能在整个网络范围内激活。只能设置为true,并且在不需要时应省略。
示例:
<?php
/**
* Plugin Name: My Basics Plugin
* Plugin URI: https://example.com/plugins/the-basics/
* Description: Handle the basics with this plugin.
* Version: 1.10.3
* Requires at least: 5.2
* Requires PHP: 7.2
* Author: John Smith
* Author URI: https://author.example.com/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: my-basics-plugin
* Domain Path: /languages
*/
<?php
/**
* Plugin Name
*
* @package PluginPackage
* @author Your Name
* @copyright 2019 Your Name or Company Name
* @license GPL-2.0-or-later
*
* @wordpress-plugin
* Plugin Name: Plugin Name
* Plugin URI: https://example.com/plugin-name
* Description: Description of the plugin.
* Version: 1.0.0
* Requires at least: 5.2
* Requires PHP: 7.2
* Author: Your Name
* Author URI: https://example.com
* Text Domain: plugin-slug
* License: GPL v2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
下面暂时快速添加:
https://developer.wordpress.org/plugins/plugin-basics/activation-deactivation-hooks/
激活钩子: register_activation_hook( __FILE__, 'pluginprefix_function_to_run' );
停用钩子: register_deactivation_hook( __FILE__, 'pluginprefix_function_to_run' );
示例:
/**
* Register the "book" custom post type
*/
function pluginprefix_setup_post_type() {
register_post_type( 'book', ['public' => true ] );
}
add_action( 'init', 'pluginprefix_setup_post_type' );
/**
* Activate the plugin.
*/
function pluginprefix_activate() {
// Trigger our function that registers the custom post type plugin.
pluginprefix_setup_post_type();
// Clear the permalinks after the post type has been registered.
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );
/**
* Deactivation hook.
*/
function pluginprefix_deactivate() {
// Unregister the post type, so the rules are no longer in memory.
unregister_post_type( 'book' );
// Clear the permalinks to remove our post type's rules from the database.
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );
卸载方法:
1、 register_uninstall_hook
register_uninstall_hook(__FILE__, 'pluginprefix_function_to_run');
2、 uninstall.php
if (!defined('WP_UNINSTALL_PLUGIN')) {
die;
}
$option_name = 'wporg_option';
delete_option($option_name);
// for site options in Multisite
delete_site_option($option_name);
// drop a custom database table
global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}mytable");
避免命名冲突 : 变量、函数、类等
示例:
if ( !class_exists( 'WPOrg_Plugin' ) ) {
class WPOrg_Plugin
{
public static function init() {
register_setting( 'wporg_settings', 'wporg_option_foo' );
}
public static function get_foo() {
return get_option( 'wporg_option_foo' );
}
}
WPOrg_Plugin::init();
WPOrg_Plugin::get_foo();
}
资源路径:
/plugin-name
plugin-name.php
uninstall.php
/languages
/includes
/admin
/js
/css
/images
/public
/js
/css
/images
插件使用js等静态资源:链接
钩子(重要)
可用钩子的的tags的列表:https://codex.wordpress.org/zh-cn:Plugin_API/Action_Reference
function wporg_callback() {
// do something
}
//https://developer.wordpress.org/reference/functions/add_action/
//add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
//第三个参数是优先级 默认 10
add_action( 'init', 'wporg_callback' );
//
创建自己的action:
https://developer.wordpress.org/reference/functions/do_action/
// The action callback function.
function example_callback( $arg1, $arg2 ) {
// (maybe) do something with the args.
}
add_action( 'example_action', 'example_callback', 10, 2 );
/*
* Trigger the actions by calling the 'example_callback()' function
* that's hooked onto `example_action` above.
*
* - 'example_action' is the action hook.
* - $arg1 and $arg2 are the additional arguments passed to the callback.
*/
$value = do_action( 'example_action', $arg1, $arg2 );
过滤器(重要)
可用的拦截器tags参考:https://codex.wordpress.org/Plugin_API/Filter_Reference
您将使用的add_filter()函数,通过至少两个参数string $tag,callable $function_to_add。
<?php
function wporg_filter_title($title)
{
return 'The ' . $title . ' was filtered';
}
add_filter('the_title', 'wporg_filter_title');
例子 要在 <body>
满足特定条件时向标签添加CSS类:
<?php
function wporg_css_body_class($classes)
{
if (!is_admin()) {
$classes[] = 'wporg-is-awesome';
}
return $classes;
}
add_filter('body_class', 'wporg_css_body_class')
定制钩子
创建自定义钩子:
需要将 do_action
for Actions 和 apply_filters
from Filters
添加回调钩子:
To add a callback function to a custom hook, use add_action() for Actions and add_filter() for Filters.
钩子尽量使用插件前缀命名
示例:
如果您的插件将设置表单添加到“管理面板”,则可以使用“操作”允许其他插件向其添加自己的设置
Foo:
Bar:
<?php
do_action( 'wporg_after_settings_page_html' );
}
现在,另一个插件可以为该wporg_after_settings_page_html钩子注册一个回调函数并注入新设置:
New 1:
<?php
}
add_action( 'wporg_after_settings_page_html', 'myprefix_add_settings' );
可扩展过滤器:
在此示例中,注册新帖子类型时,定义它的参数将通过过滤器传递,因此另一个插件可以在创建帖子类型之前对其进行更改。
<?php
function wporg_create_post_type()
{
$post_type_params = [/* ... */];
register_post_type(
'post_type_slug',
apply_filters( 'wporg_post_type_params', $post_type_params )
);
}
现在,另一个插件可以为该wporg_post_type_params钩子注册一个回调函数并更改发布类型参数:
<?php
function myprefix_change_post_type_params( $post_type_params ) {
$post_type_params['hierarchical'] = true;
return $post_type_params;
}
add_filter( 'wporg_post_type_params', 'myprefix_change_post_type_params' );
高级主题 略
管理菜单
顶层菜单
<?php
//https://developer.wordpress.org/reference/functions/add_menu_page/
//add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '', string $icon_url = '', int $position = null )
add_menu_page(
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
callable $function = '',
string $icon_url = '',
int $position = null
);
例子:
假设我们要添加一个名为“ WPOrg”的新顶层菜单。
第一步将是创建一个输出HTML的函数。在此功能中,我们将执行必要的安全检查,并使用Settings API呈现我们已注册的选项。
<?php
function wporg_options_page_html() {
?>
<div class="wrap">
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
<form action="options.php" method="post">
<?php
// output security fields for the registered setting "wporg_options"
settings_fields( 'wporg_options' );
// output setting sections and their fields
// (sections are registered for "wporg", each field is registered to a specific section)
do_settings_sections( 'wporg' );
// output save settings button
submit_button( __( 'Save Settings', 'textdomain' ) );
?>
</form>
</div>
<?php
}
?>
第二步将是注册我们的WPOrg菜单。在admin_menu动作挂钩期间需要进行注册。
<?php
add_action( 'admin_menu', 'wporg_options_page' );
function wporg_options_page() {
add_menu_page(
'WPOrg',
'WPOrg Options',
'manage_options',
'wporg',
'wporg_options_page_html',
plugin_dir_url(__FILE__) . 'images/icon_wporg.png',
20
);
}
?>
对HTML使用PHP文件
可移植代码的最佳实践是创建一个需要/包含您的PHP文件的回调。
为了完整性并帮助您理解旧代码,我们将展示另一种方式:将a PHP file path作为$menu_slug参数与参数一起传递null $function。
<?php
add_action( 'admin_menu', 'wporg_options_page' );
function wporg_options_page() {
add_menu_page(
'WPOrg',
'WPOrg Options',
'manage_options',
plugin_dir_path(__FILE__) . 'admin/view.php',
null,
plugin_dir_url(__FILE__) . 'images/icon_wporg.png',
20
);
}
?>
删除顶层菜单
<?php
remove_menu_page(
string $menu_slug
);
?>
<?php
add_action( 'admin_menu', 'wporg_remove_options_page', 99 );
function wporg_remove_options_page() {
remove_menu_page( 'tools.php' );
}
?>
提交表单
子菜单
add_submenu_page()
add_submenu_page(
string $parent_slug,
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
callable $function = ''
);
B站视频教程:https://www.bilibili.com/video/BV1St411s7bm?p=2
哔哩哔哩的学习记录
启用创建时运行: register_activation_hook(__FILE__,'func')
停用插件时运行: register_deactivation_hook(__FILE__,'func')
更新WP配置表 update_action("key","value")
添加钩子: add_action("hook_name",'func')
获取配置: get_option("key")
wp操作数据库:
global $wpdb;
查找存在表 创建数据库表
if($wpdb->get_var("SHOW TABLES LIKE '{$wpdb->prefix}test'" != "{$wpdb->prefix}test"){
$wpdb->query('create_table_sql');
$wpdb->query('insert_data_sql');
}
//读取数据
// 注意这里获取前缀 {$wpdb->prefix}
$wpdb->get_rew("sql");
表单提交的安全验证信息:
wp_nonce_field('hc_test_nonce')
验证:check_admin_referer('ch_test_nonce')
更新操作:$wpdb->update("{$wpdb->prefix}test",array('color'=>$_POST['color']),array('id'=>1))
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 anaf@163.com