1.咱们为何要建立一个插件?php
2.你但愿你的插件具备什么功能?web
尽管咱们在梳理开发流程中已经提到了如何建立一个插件,可是咱们仍是要再说一次,以防有些读者没有看到。redis
1.打开WordPress安装目录下的wp-content
目录。网络
2.打开plugins
目录。svg
3.建立一个新目录并在插件后命名(例如plugin-name
)。wordpress
4.打开新插件的目录。函数
5.建立一个新的PHP文件(例如,在插件后命名此文件也很好plugin-name.php
)。布局
就像下面的示例同样,你必须在你建立的主插件文件的开头加上一段doc
注释来告诉wordpress这是个插件,固然也能够加上做者,邮箱等信息,下面只是简单示例,详细能够在咱们梳理流程的那边博文/或者官网中看到。post
//wp-content/plugin-name/plugin-name.php <?php /** * Plugin Name: 插件名称 */ function do_something_else() { //.....你的代码 }
还记得咱们在第一篇梳理中提到的三个基础插件钩子么?this
1.register_activation_hook //启用插件时触发的钩子
2.register_deactivation_hook//禁用插件时触发的钩子
3.register_uninstall_hook//删除插件时触发的钩子
咱们能够经过这三个钩子函数来作一下一些前置/后置的处理,好比说插件被启用时建立一个自定义数据表,初始化一些配置,禁用时恢复初始化设置,删除时删除自定义的数据表。
这里咱们先不展开来说咱们在讲OptionApi
的时候再讲这个。
准备工做都已经作好了,咱们如今开始正式的开发。咱们假设说咱们要作的是一个额外的内容管理插件。那咱们如今想要在后台建立一个定制内容管理
菜单,该怎么作呢?
wordpress向咱们提供了一个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 //位置 决定了菜单应该插入在第几个 ); **/
那咱们应该怎么使用呢?
for-example :
你的wp-content/plugin-name/plugin-name.php
文件,看起来应该像这样:
<?php /* Plugin Name: 定制内容管理 Plugin URI: http://ergou.fun Description: 内容管理模块(自定义内容非posts) Version: 1.0 Author: ergou Author URI: http://ergou.fun Copyright 2019 ergou (email : 531432012@qq.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** 第1步:建立自定义菜单的函数**/ function ergou_cms_plugin_menu() { add_menu_page('定制内容管理', '内容管理', 'manage_options', 'ergou-cms-manager', 'ergou_cms_plugin_options', '', 7); } /** 第2步:将函数注册到钩子中 */ add_action('admin_menu', 'ergou_cms_plugin_menu'); /** 第3步:定义选项被点击时打开的页面 */ function ergou_cms_plugin_options() { if (!current_user_can('manage_options')) { wp_die(__('You do not have sufficient permissions to access this page.')); } //include_once(plugin_dir_path(__FILE__) . 'detail/index.php'); //也能够直接返回HTML,不过我建议是额外放一个文件,这样之后维护起来好处理 //你能够直接 echo "hello world" echo "Hello World"; wp_die(); }
咱们如今回到咱们的后台管理页面点击插件管理
你会发现多了一个,定制内容管理的菜单,点击启用。菜单就会增长在左侧顶级菜单里。点击定制内容管理
菜单,页面输出了"Hello World"
。至此,咱们算是完成了第一步。
本篇内容就是这些。That’s all .Thank you .