返回上一级
WordPress为后台页面创建表单选项
不废话,先上官方推荐做法
以下展示所有表单选项
1<?php
2add_action('admin_menu', function () {
3 add_menu_page(
4 '我是最棒的设置', // 页面内标题
5 '最棒的设置', // 左侧侧边栏名称
6 'manage_options', // 菜单类型
7 'i_am_good_setting_slug', // 唯一 id (slug)
8 function () { // 匿名函数输出页面的内容
9 if (!current_user_can('manage_options')) { // 如果没有管理页权限则退出
10 return;
11 }
12 ?>
13 <div class="wrap">
14 <h1><?php echo esc_html(get_admin_page_title()); //输出标题
15 ?></h1>
16 <h2>官方接口</h2>
17 <form action="options.php" method="post">
18 <?php
19 // 安全,限可制修改范围,去掉后保存会跳转到 ./wp-admin/options.php,内容为设置组
20 settings_fields('i_am_good_settings');
21 // 显示,内容为设置组
22 do_settings_sections('i_am_good_settings');
23 // 保存按钮
24 submit_button('保存设置');
25 ?>
26 </form>
27 </div>
28<?php
29 },
30 plugin_dir_url(__FILE__) . 'images/icon.svg', // 图标位置
31 20 // 菜单顺序中的位置
32 );
33});
34
35add_action('admin_init', function () {
36 // 在 {$wpdb->prefix}_options 表中创建一个条目。 删掉后保存会报错,(设置组,数据库保存的变量名)
37 register_setting('i_am_good_settings', 'i_am_good_options');
38
39 // 添加一个设置部分
40 add_settings_section(
41 'i_am_good_section', // id
42 'demo的设置部分', // 标题
43 '', // 回调函数
44 'i_am_good_settings' // 设置组
45 );
46
47 // 在《部分》里添加字段
48 add_settings_field(
49 'i_am_good_option1', // 标签的唯一id
50 '下拉框', // 选项的名称
51 'i_am_good_option1', // 回调函数,里面写输出选项的html
52 'i_am_good_settings', // 设置组
53 'i_am_good_section', // 设置部分的id
54 array(
55 'label_for' => 'option1', // wp数据库这个字段的 key,[key:value,key:value]。删掉后保存则保存数组[value,value]
56 )
57 );
58
59 add_settings_field(
60 'i_am_good_option2',
61 '输入框',
62 'i_am_good_option2',
63 'i_am_good_settings',
64 'i_am_good_section',
65 array(
66 'label_for' => 'option2',
67 )
68 );
69
70 add_settings_field(
71 'i_am_good_option3',
72 '选择框',
73 'i_am_good_option3',
74 'i_am_good_settings',
75 'i_am_good_section',
76 array(
77 'label_for' => 'option3',
78 )
79 );
80
81 add_settings_field(
82 'i_am_good_option4',
83 '选择框2',
84 'i_am_good_option4',
85 'i_am_good_settings',
86 'i_am_good_section',
87 array(
88 'label_for' => 'option4',
89 )
90 );
91
92 add_settings_field(
93 'i_am_good_option5',
94 '单选框',
95 'i_am_good_option5',
96 'i_am_good_settings',
97 'i_am_good_section',
98 array(
99 'label_for' => 'option5',
100 )
101 );
102
103 add_settings_field(
104 'i_am_good_option6',
105 '文本框',
106 'i_am_good_option6',
107 'i_am_good_settings',
108 'i_am_good_section',
109 array(
110 'label_for' => 'option6',
111 )
112 );
113});
114
115
116function i_am_good_option1($args)
117{
118 $options = get_option('i_am_good_options');
119?>
120 <select id="<?php echo esc_attr($args['label_for']); ?>" name="i_am_good_options[<?php echo esc_attr($args['label_for']); ?>]">
121 <option value="red" <?php echo isset($options[$args['label_for']]) ? (selected($options[$args['label_for']], 'red', false)) : (''); ?>>
122 <?php esc_html_e('红色药丸'); ?>
123 </option>
124 <option value="blue" <?php echo isset($options[$args['label_for']]) ? (selected($options[$args['label_for']], 'blue', false)) : (''); ?>>
125 <?php esc_html_e('蓝色药丸'); ?>
126 </option>
127 <option value="green" <?php echo isset($options[$args['label_for']]) ? (selected($options[$args['label_for']], 'green', false)) : (''); ?>>
128 <?php esc_html_e('绿色药丸'); ?>
129 </option>
130 </select>
131 <p class="description">
132 <?php esc_html_e('你吃下蓝色药丸,故事就结束了。你从床上醒来,相信你想相信的一切。'); ?>
133 </p>
134 <p class="description">
135 <?php esc_html_e('你吃了红色药丸,你就会留在仙境,我就让你看看兔子洞有多深。'); ?>
136 </p>
137<?php
138}
139
140function i_am_good_option2($args)
141{
142 $options = get_option('i_am_good_options')[$args['label_for']] ?? '';
143?>
144 <input id="<?php echo esc_attr($args['label_for']); ?>" name="i_am_good_options[<?php echo esc_attr($args['label_for']); ?>]" value="<?php echo $options; ?>">
145<?php
146}
147
148function i_am_good_option3($args)
149{
150 $options = get_option('i_am_good_options')[$args['label_for']] ?? '0';
151?>
152 <input id="<?php echo esc_attr($args['label_for']); ?>" type="checkbox" name="i_am_good_options[<?php echo esc_attr($args['label_for']); ?>]" value="1" <?php echo $options ? 'checked' : ''; ?>>
153 任何人都能变成超人
154 <?php
155}
156
157function i_am_good_option4($args)
158{
159 $options = get_option('i_am_good_options')[$args['label_for']] ?? [];
160 $list = ['苹果', 'oppo', '小米', '华为', 'vivo'];
161 echo '<fieldset>';
162 foreach ($list as $key => $value) {
163 $checked = $options[$key] ?? '';
164 ?>
165 <input id="<?php echo esc_attr($args['label_for']) . '[' . $key . ']'; ?>" type="checkbox" name="i_am_good_options[<?php echo esc_attr($args['label_for']); ?>][<?php echo $key ?>]" value="1" <?php echo $checked ? 'checked' : ''; ?>>
166 <?php echo $value;
167 }
168 echo '</fieldset>';
169}
170
171function i_am_good_option5($args)
172{
173 $options = get_option('i_am_good_options')[$args['label_for']] ?? '0';
174 $list = ['秘密', '男', '女', '沃尔玛购物袋'];
175 echo '<fieldset>';
176 foreach ($list as $key => $value) {
177 ?>
178 <label>
179 <input id="<?php echo esc_attr($args['label_for']) . '[' . $key . ']'; ?>" type="radio" name="i_am_good_options[<?php echo esc_attr($args['label_for']); ?>]" value="<?php echo $key ?>" <?php echo $options == $key ? 'checked' : ''; ?>>
180 <span><?php echo $value; ?></span>
181 </label>
182 <br>
183 <?php
184 }
185 echo '</fieldset>';
186}
187
188function i_am_good_option6($args)
189{
190 $options = get_option('i_am_good_options')[$args['label_for']] ?? '';
191 ?>
192 <textarea id="<?php echo esc_attr($args['label_for']); ?>" name="i_am_good_options[<?php echo esc_attr($args['label_for']); ?>]" rows="10" cols="50"><?php echo $options; ?></textarea>
193<?php
194}
选项很简单,但是如果我需要对表格进行操作呢?
来看看用wordpress官方类来实现操作。
注意,wordpress不建议你使用此类,原因是以后可能会有变动。
但事实上你会发现很多插件都用了此类来实现表格。
不废话,上代码:
1<?php
2add_action('admin_menu', function () {
3 add_menu_page(
4 '我是最棒的设置', // 页面内标题
5 '最棒的设置', // 左侧侧边栏名称
6 'manage_options', // 菜单类型
7 'i_am_good_setting_slug', // 唯一 id (slug)
8 function () { // 匿名函数输出页面的内容
9 if (!current_user_can('manage_options')) { // 如果没有管理页权限则退出
10 return;
11 }
12 ?>
13 <div class="wrap">
14 <h1><?php echo esc_html(get_admin_page_title()); //输出标题
15 ?></h1>
16 <h2>WP_List_Table 表格</h2>
17 <?php
18 $testListTable = new I_Am_Good_List_Table();
19 $testListTable->prepare_items(); ?>
20 <form id="movies-filter" method="get">
21 <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" />
22 <?php $testListTable->display() ?>
23 </form>
24 </div>
25<?php
26 },
27 plugin_dir_url(__FILE__) . 'images/icon.svg', // 图标位置
28 20 // 菜单顺序中的位置
29 );
30});
31
32/**
33 * https://developer.wordpress.org/reference/classes/wp_list_table/
34 */
35if ( ! class_exists( 'WP_List_Table' ) ) { // 确保能找到类!
36 require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
37}
38class I_Am_Good_List_Table extends WP_List_Table
39{
40 // 构造函数
41 function __construct()
42 {
43 global $status, $page;
44
45 //Set parent defaults
46 parent::__construct(array(
47 'singular' => 'movie', //singular name of the listed records
48 'plural' => 'movies', //plural name of the listed records
49 'ajax' => false //does this table support ajax?
50 ));
51 }
52 // 初始化列表方法
53 function prepare_items()
54 {
55 // global $wpdb;
56 // $sql="SELECT COUNT(*) as numbers FROM `zhongyidc`";
57 $per_page = 5;
58 $columns = $this->get_columns();
59 $hidden = array();
60 $sortable = $this->get_sortable_columns();
61 $this->_column_headers = array($columns, $hidden, $sortable);
62 $this->process_bulk_action();
63 $data = [[
64 'ID' => 1,
65 'title' => '300',
66 'rating' => 'R',
67 'director' => 'Zach Snyder',
68 'phone' => '13336756456'
69 ], [
70 'ID' => 2,
71 'title' => '400',
72 'rating' => 'G',
73 'director' => 'Zach Snyder',
74 'phone' => '15435465576'
75 ],];
76 function usort_reorder($a, $b)
77 {
78 $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title';
79 $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
80 $result = strcmp($a[$orderby], $b[$orderby]);
81 return ($order === 'asc') ? $result : -$result;
82 }
83 usort($data, 'usort_reorder');
84 $current_page = $this->get_pagenum();
85 $total_items = count($data);
86 $data = array_slice($data, (($current_page - 1) * $per_page), $per_page);
87 $this->items = $data;
88 $this->set_pagination_args(array(
89 'total_items' => $total_items,
90 'per_page' => $per_page,
91 'total_pages' => ceil($total_items / $per_page)
92 ));
93 }
94 // 自定义列内容处理
95 function column_ID($item)
96 {
97 //Build row actions
98 $actions = array(
99 'edit' => sprintf('<a href="?page=%s&action=%s&movie=%s">编辑', $_REQUEST['page'], 'edit', $item['ID']),
100 'delete' => sprintf('<a href="?page=%s&action=%s&movie=%s">删除', $_REQUEST['page'], 'delete', $item['ID']),
101 );
102
103 //Return the title contents
104 return sprintf(
105 '%1$s%2$s',
106 /*$1%s*/
107 $item['ID'],
108 /*$2%s*/
109 $this->row_actions($actions)
110 );
111 }
112 // 默认列内容处理
113 function column_default($item, $column_name)
114 {
115 switch ($column_name) {
116 case 'title':
117 case 'rating':
118 case 'director':
119 case 'phone':
120 return $item[$column_name];
121 default:
122 return print_r($item, true); //Show the whole array for troubleshooting purposes
123 }
124 }
125 // 多选处理
126 function column_cb($item)
127 {
128 return sprintf(
129 '<input type="checkbox" name="%1$s[]" value="%2$s" />',
130 /*$1%s*/
131 $this->_args['singular'], //Let's simply repurpose the table's singular label ("movie")
132 /*$2%s*/
133 $item['ID'] //The value of the checkbox should be the record's id
134 );
135 }
136 // 动作处理函数
137 function process_bulk_action()
138 {
139 //Detect when a bulk action is being triggered...
140 if ('delete' === $this->current_action()) {
141 wp_die('Items deleted (or they would be if we had items to delete)!');
142 }
143 }
144 // 动作数组关联
145 function get_bulk_actions()
146 {
147 $actions = array(
148 'delete' => '删除'
149 );
150 return $actions;
151 }
152 // 列是否允许排序
153 function get_sortable_columns()
154 {
155 $sortable_columns = array(
156 'title' => array('title', false), //true means it's already sorted
157 'rating' => array('rating', false),
158 'director' => array('director', false)
159 );
160 return $sortable_columns;
161 }
162 // 列标题设置
163 function get_columns()
164 {
165 $columns = array(
166 'cb' => '<input type="checkbox" />', //选择框
167 'ID' => 'user id',
168 'title' => '金额',
169 'rating' => '类型',
170 'director' => '地址',
171 'phone' => '电话'
172 );
173 return $columns;
174 }
175}
我们发现相当复杂且繁琐,我仅仅需要一个表单,却要填写这么多代码,非常不优雅。
那有没有简介的办法呢
答案当然是有的,我们可以通过适当的骚操作实现这一过程。
不废话,上代码。
1<?php
2add_action('admin_menu', function () {
3 add_menu_page(
4 '我是最棒的设置', // 页面内标题
5 '最棒的设置', // 左侧侧边栏名称
6 'manage_options', // 菜单类型
7 'i_am_good_setting_slug', // 唯一 id (slug)
8 function () { // 匿名函数输出页面的内容
9 if (!current_user_can('manage_options')) { // 如果没有管理页权限则退出
10 return;
11 }
12 $options = [ // 获取表格
13 ['id' => 0, 'name' => "玛卡巴卡", 'age' => '5'],
14 ['id' => 1, 'name' => "太阳公公", 'age' => '500']
15 ];
16 if (isset($_POST['submit'])) {
17 switch ($_POST['submit']) {
18 case '删除':
19 // 修改你的删除函数
20 add_settings_error('wporg_messages', 'wporg_message', '你点击id为' . ($_POST['key'] ?? '') . '的删除', 'updated');
21 break;
22 case '上移':
23 // 修改你的函数
24 add_settings_error('wporg_messages', 'wporg_message', '你点击id为' . ($_POST['key'] ?? '') . '的上移', 'updated');
25 break;
26 case '下移':
27 // 修改你的函数
28 add_settings_error('wporg_messages', 'wporg_message', '你点击id为' . ($_POST['key'] ?? '') . '的下移', 'updated');
29 break;
30 case '编辑':
31 // 修改你的函数
32 add_settings_error('wporg_messages', 'wporg_message', '你点击id为' . ($_POST['key'] ?? '') . '的编辑', 'updated');
33 break;
34 case '添加':
35 // 修改你的函数
36 break;
37 }
38 }
39 settings_errors('wporg_messages'); // 输出提示窗
40 ?>
41 <div class="wrap">
42 <h1><?php echo esc_html(get_admin_page_title()); //输出标题
43 ?></h1>
44 <h2>简单版 表格</h2>
45 <table class="widefat striped">
46 <thead>
47 <tr>
48 <th>id</th>
49 <th>名字</th>
50 <th>年龄</th>
51 <th>操作</th>
52 </tr>
53 </thead>
54 <tbody>
55 <?php
56 foreach ($options as $key => $value) {
57 echo '<tr>';
58 echo '<td>' . ($value['id'] ?? "") . '</td>';
59 echo '<td>' . ($value['name'] ?? "") . '</td>';
60 echo '<td>' . ($value['age'] ?? "") . '</td>';
61 echo '<td>';
62 echo '<form action="" method="post"><input style="display:none;" name="key" value="' . $key . '" />
63 <input type="submit" name="submit" value="编辑" class="button button-small" />
64 <input type="submit" name="submit" value="上移" class="button button-small" ' . ($key == 0 ? "disabled" : "") . '/>
65 <input type="submit" name="submit" value="下移" class="button button-small" ' . ($key == count($options) - 1 ? "disabled" : "") . '/>
66 <input type="submit" name="submit" value="删除" class="button button-small" /></form>';
67 echo '</td>';
68 echo '</tr>';
69 }
70 ?>
71
72 </tbody>
73 </table>
74 </div>
75<?php
76 },
77 plugin_dir_url(__FILE__) . 'images/icon.svg', // 图标位置
78 20 // 菜单顺序中的位置
79 );
80});
简单的代码,实现了表格所有重要操作。
在form里为按钮设置不同的value,在接收的时候加以区分,就能实现按钮的不同操作,包括不限于增删查改。
同时在form里设置一个隐藏的input,就实现提交时候的传参。
1<form action="" method="post">
2 <!-- 隐藏,负责提交时传参 -->
3 <input style="display:none;" name="key" value="' . $key . '" />
4 <!-- 显示,操作按钮 -->
5 <input type="submit" name="submit" value="编辑" class="button button-small" />
6 <input type="submit" name="submit" value="上移" class="button button-small" />
7 <input type="submit" name="submit" value="下移" class="button button-small" />
8 <input type="submit" name="submit" value="删除" class="button button-small" />
9</form>