here an example of how to manage multiple set of options. it needs to be completed by a nonce to avoid CSRF attack and it needs also a little bit of layout.
add_action("admin_menu", function () {
add_menu_page(
"Multioptions"
, "Multioptions"
, "manage_options" // capability to be allowed to edit options
, "MY_PLUGIN__multioptions"
, function () {
do_action("MY_PLUGIN/multioptions");
}
);
});
add_filter("MY_PLUGIN/list_options", function ($list_options) {
return [
"option1" => [
"label" => "Put your hands up in the air",
],
"option2" => [
"label" => "Put your hands up",
],
"option3" => [
"label" => "In the air",
],
];
});
add_action("MY_PLUGIN/multioptions", function () {
$current_user = wp_get_current_user();
$values = $current_user->MY_PLUGIN__values;
if ("" === $values) {
$values = [[]];
}
?>
<div class="MY_PLUGIN__multioptions">
<?php
if ( !isset($_GET["id_set"])
|| !isset($values[$_GET["id_set"]])
) {
do_action("MY_PLUGIN/multioptions/show_sets", $values);
} else {
do_action("MY_PLUGIN/multioptions/edit_a_set", $_GET["id_set"], $values[$_GET["id_set"]]);
}
?>
</div>
<style>
.MY_PLUGIN__multioptions div
{
margin : 2em;
}
</style>
<?php
});
add_action("MY_PLUGIN/multioptions/show_sets", function ($values) {
?>
<?php foreach (array_keys($values) as $id_set) {?>
<div>
<a href="?page=<?= htmlspecialchars($_GET["page"])?>&id_set=<?= htmlspecialchars($id_set)?>">
edit set <?= htmlspecialchars($id_set)?></a>
</div>
<?php }?>
<div>
<form method="post">
<button name="add_set">add a set</button>
</form>
</div>
<?php
}, 10, 1);
add_action("MY_PLUGIN/multioptions/edit_a_set", function ($id_set, $values_set) {
$list_options = apply_filters("MY_PLUGIN/list_options", NULL);
$message = $_GET["message"] ?? "";
?>
<h3>
set number <?= htmlspecialchars($id_set)?>
</h3>
<?php if ("saved" === $message) {?>
<div id="message" class="notice notice-success is-dismissible updated">
<p>Saved</p>
</div>
<?php }?>
<form method="post">
<button name="save">save</button>
<?php foreach ($list_options as $option_key => $tab_option) {?>
<div>
<label>
<?= htmlspecialchars($tab_option["label"])?>
<input
type="checkbox"
name="<?= htmlspecialchars($option_key)?>"
<?= !isset($values_set[$option_key]) ? "" : " checked=\"checked\""?>
/>
</label>
</div>
<?php }?>
<button name="save">save</button>
</form>
<?php
}, 10, 2);
add_action("load-toplevel_page_MY_PLUGIN__multioptions", function () {
$current_user = wp_get_current_user();
$values = $current_user->MY_PLUGIN__values;
if ("" === $values) {
$values = [[]];
}
if (isset($_POST["save"])) {
// save a set
unset($_POST["save"]);
$values[$_GET["id_set"]] = $_POST;
update_user_meta($current_user->ID, "MY_PLUGIN__values", $values);
// redirection
wp_redirect($_SERVER["REQUEST_URI"] . "&message=saved", 303);
exit();
}
if (isset($_POST["add_set"])) {
// add a set
$values[] = [];
update_user_meta($current_user->ID, "MY_PLUGIN__values", $values);
// redirection
wp_redirect($_SERVER["REQUEST_URI"], 303);
exit();
}
});