zl程序教程

您现在的位置是:首页 >  后端

当前栏目

WordPress二次开发之将插件集成到WordPress现有管理界面

集成WordPress插件 管理 界面 二次开发 现有
2023-06-13 09:12:32 时间

之前开发的方式是创建菜单->创建页面->编写代码 这种开发插件的方式比较麻烦,如果只是一些小的功能,小的配置,我们完全可以将其集成到现有的WordPress

将上一篇文章的插件代码精简如下

<?php
/*
Plugin Name:test_install
Description:这是描述
Author:tzh
Version:0.0.1
*/
// 创建菜单
class my_change_font_style{
    var $option_group = 'general'; //注册选项 设置显示在哪个页面

    public function __construct()
    {
        add_action('admin_init',array($this,'register_my_test_setting'));
        add_action('wp_head',array($this,'my_test_head_fun'));
    }
    
    public function register_my_test_setting(){
        //注册一个选项,用于装载所有插件设置项
        register_setting($this->option_group,'my_test_option');
        //设置字段
        /**
         * 字段id
         * 字段标题
         * 输出字段的方法
         * 字段分组
         * 字段展示区域
         */ 
        add_settings_field(
            'my_test_color',
            '字体颜色',
            array($this,'my_test_color_function'),
            $this->option_group
        );
        //设置字段 字体大小
        add_settings_field(
            'my_test_size',
            '字体大小',
            array($this,'my_test_size_function'),
            $this->option_group
        );
    }
    
    //字体颜色
    public function my_test_color_function(){
        //获取选项  之前用register_setting注册的选项
        $my_test_option = get_option('my_test_option');
        ?>
        <!-- name值为 要保存的字段名称 = 选项名称(my_test_option)+[字段名称] -->
        <input type="text" name="my_test_option[color]" value="<?php echo $my_test_option['color']?>">
        <?php
    }
    //字体大小
    public function my_test_size_function(){
        $my_test_option = get_option('my_test_option');
        $size = $my_test_option['size'];
        ?>
        <select name="my_test_option[size]" id="">
            <option value="12" <?php selected('12',$size)?>>12</option>
            <option value="14" <?php selected('14',$size)?>>14</option>
        </select>
        <?php
    }
    public function my_test_setting_section_function(){
        ?><p>设置字体样式</p><?php
    }
    public function my_test_head_fun(){
        $my_test_option = get_option('my_test_option');//获取选项组
        ?>
        <style>
            body{
                color:<?php echo $my_test_option['color']?>;
                font-size: <?php echo $my_test_option['size']?>;
            }
        </style>
        <?php
         
    }

    
}
new my_change_font_style();

我们取消了页面初始布局,左侧菜单,字段的展示区域等 新增 var $option_group = 'general'属性 该属性用于设置 选项的展示区域 与设置子菜单对应

取对应的值展示到对应的区域