wordpress网站设置中添加设置项

目标是将如上的设置常规选现中添加一些扩展字段,在wordpress主题函数functions.php中添加如下代码 


function hx_add_field()
{
    $global_seo = new Hxfield();
    $global_seo->setting_fields();
}

add_action('admin_init', 'hx_add_field');

class Hxfield
{
    public function setting_fields()
    {
        $text_input = [
            'newfield1' => '新字段1',
            'newfield2' => '新字段2',

        ];
        $textarea_input = ['seo_description' => '测试多行文本'];
        foreach ($text_input as $key => $val) {
            $this->sonliss_settings_field($key, $val, 'sonliss_textbox_callback', [$key]);
            $this->sonliss_register_setting($key);
        }
        foreach ($textarea_input as $key => $val) {
            $this->sonliss_settings_field($key, $val, 'sonliss_textareabox_callback', [$key]);
            $this->sonliss_register_setting($key);
        }
    }

    /**
     * id ID
     * title 显示在页面的标题即label
     * callback 回调
     * args []
     */
    public function sonliss_settings_field($id, $title, $callback, $args)
    {
        add_settings_field(
            $id,
            $title,
            [$this, $callback],
            'general', // general, reading, writing, discussion, media
            'default', // 块,对应add_settings_section的id
            $args
        );
    }

    /**
     * id ID
     */
    public function sonliss_register_setting($id)
    {
        register_setting('general', $id);
    }

    /**
     * input text
     */
    public function sonliss_textbox_callback($args)
    {
        $option = get_option($args[0]);
        echo '<input type="text" id="' . $args[0] . '" name="' . $args[0] . '" value="' . $option . '" class="regular-text" />';
    }

    /**
     * area
     */
    public function sonliss_textareabox_callback($args)
    {
        $option = get_option($args[0]);
        echo '<textarea id="' . $args[0] . '" name="' . $args[0] . '" class="regular-text">' . $option . '</textarea>';
    }
}

实现的效果如下图

我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器