6

Is there a way of adding settings fields dynamically?

I have my own Settings API options generator just like in Chip Bennet's Oenology Theme, everything works perfect but I can't find a way to create dynamic fields.

Here's how I add option fields.

1. First I describe all fields:

 function my_options() {
    $options = array(
         array(
            'id' => '1',
            'title' => '1', 
            'type' => 'foo',
            'description' =>  'bar',
        ),
          array(
            'id' => '2',
            'title' => '2', 
            'type' => 'foo',
            'description' =>  'bar',
        ),
    );

   return $options;
 }

2. Then I generate fields:

foreach(my_options() as $field) {
    add_settings_field(
       $field['id'],
       $field['title'],
       "something",
       "else",
       "goes",
       "there"
    );
}

Then doing:

   <?php $opts = get_option('my_theme_settings_api'); 
   var_dump($opts); ?>

Returns all the fields.

But what If want to generate some of the fields "on the fly", eg. based on some other array, just like that:

function my_options() {

   // $myarray = some array of elements taken from different source, like json data from other website etc.
   $count = 0;
   foreach($myarray as $something) {
        $count++;
        $options[] = array(
            'id' => 'something'. $count,
            'title' => $something['title'],
            'type' => 'type',
            'desription' => $something['description'],
        );

   return $options;
 }

Then I'm getting the fields displayed using do_settings_sections() but I can't save them on admin pages and when I do var_dump($opts); just like in example above these options doesn't exist there.

Any clues?

0

It sounds like you would need a way to get those dynamic fields into the my_options function each time it's called. You could try creating your own filter to use:

function my_options() {
    $myarray = apply_filters( 'my_get_options_dynamically', array() );
    $count   = 0;

    foreach($myarray as $something) {
        $count++;
        $options[] = array(
            'id'         => 'something'. $count,
            'title'      => $something['title'],
            'type'       => 'type',
            'desription' => $something['description'],
        );

        return $options;
}

add_filter( 'my_get_options_dynamically', function() {
    // Some code to get the dynamic option array.
    return array( array(
        'title'       => 'Some option title',
        'description' => 'Some option description',
    ) );
} );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.