Print This Post

WordPress Settings: Dynamic Fields

When you have a lot of settings fields with the same type, it is often annoying to write a display function for every field.
There is a simple and better way to do this.

Example:
You want to make a checkbox for every menu in from WordPress administration.
First you get the menus:

$menus = $GLOBALS[‘menu’];

Now we create a new settings section:

add_settings_section(“menu-test-section-“, “”, “”, “menu-test-options”);

Now traverse through every menu entry, create a settings field and register this field.

foreach ($menus as $menukey => $menuvalue) {
    if (!empty($menuvalue[0])) { // Not a separator?
        $label = $menuvalue[0]; // Title of menu entry
        $fieldname = "menu-test-field-".$menukey;
        $id = $fieldname . "-id";
        // Now comes the funny part
        // Anonymous display function
        $callback = function() use ($id, $label, $fieldname) {
            ?>
                <label for="<?php echo $id; ?>"><?php echo $label; ?></label>
                <input id="<?php echo $id; ?>" name="<?php echo $fieldname; ?>" type="checkbox" value="1" <?php checked(1, get_option($fieldname),true);?> />
        };
        add_settings_field($fieldname, "", $callback, "menu-test-options", "menu-test-section");
        register_setting("menu-test-section", $fieldname);
    }
}

That’s all!

Kommentare

Keine Kommentare bisher

Hinterlassen Sie einen Kommentar