How to Loop Plugin Option Field Set?

I figured it out after a little work.

To start, I ended up using a single callback: array($this, 'txs_loop_callbacks') using the same add_settings_field registration above. Then I altered the final argument in the field resgistration, making each unique to that specific field: array('field' => 'txs_opacity_'.$i).

Then in the loop callback I stored each field’s HTML in a anonymous function defined as a variable. Like so:

$txs_checkbox = function($num) {
    $is_checked = checked( isset($this->txsoptions['rangers_txs_checkbox_'.$num]), true, false);
    printf(
       '<input type="checkbox" class="is-important-'.$num.'" id="rangers_txs_checkbox_'.$i.'" name="rangers_txs_option[rangers_txs_checkbox_'.$num.']" %1$s />
        <label for="rangers_txs_option[rangers_txs_checkbox_'.$num.']">District '.$num.' is important</label><br /><br />', 
        $is_checked
    );
};

I defined this type of variable for each field type (i.e., $txs_checkbox, $txs_colorpicker, and on).

After that, I called the anonymous functions inside a loop with a check to display only one kind of field per set.

$n=1;
while($n <= 31) {
    switch($args['field']):
        case('txs_checkbox_'.$n):
            $txs_checkbox($n);
            break;

        case('txs_colorpicker_'.$n):
            $txs_colorpicker($n);
            break;

        case('txs_opacity_'.$n):
            $txs_opacity($n);
            break;

        case('txs_info_'.$n):
            $txs_info($n);
            break;
    endswitch;

    $n++;
}

With those elements all together, I was able to achieve the result of repeating field sets.

Leave a Comment