Dynamic settings fields with Settings API

This issue is now resolved. I am posting the solution, in case someone else finds it useful.

I have modified my callback for adding the checkbox list of categories so that the selected categories are saved in an array instead of separate options. It will make it much easier to find said special category and matching it with queried_object in the front end.

function bcio_fp_special_cats_display(){
$options = (array)get_option('bcio_options');
$categories = bcio_get_categories();

echo '<ul>';

foreach($categories as $category){
    $selected = ( isset( $options['fp_sp_category'] ) ) ? $options['fp_sp_category'] : '';  

    if(in_array($category->cat_ID, $selected)){ 
        echo '<li><input type="checkbox" value="'.$category->cat_ID.'" name="bcio_options[fp_sp_category][]" checked/>'.$category->name.'</li>';

    } else {
        echo '<li><input type="checkbox" value="'.$category->cat_ID.'" name="bcio_options[fp_sp_category][]"/>'.$category->name.'</li>';            
    }       

}

echo '</ul>';


}

Based on the values contained in this new array (category ids), I then generate the setting fields, with the category ID as an argument to the field:

function bcio_special_section_settings_display(){
echo "These settings fields are generated based on your selection of Special Front Page Categories";
$options = (array)get_option('bcio_options');
$selected = ( isset( $options['fp_sp_category'] ) ) ? $options['fp_sp_category'] : '';  

      if($selected){    
      foreach($selected as $cat_id){
        add_settings_field( 
             'section_'.$cat_id,                    
             'Special Section:<br />'.get_cat_name( $cat_id ),          
             'bcio_special_section_display',        
             'business-cover-special-sections', 
             'bcio_special_sections_options', 
             $cat_id                
      );  
      }             
}
}

I then used the argument to give my field a unique ID, and to save the color option as color_$mycatid.

function bcio_special_section_display($args){
$special_options = (array)get_option('bcio_special_options');
$color =  ( isset( $special_options['color_'.$args] ) ) ? $special_options['color_'.$args] : '';
echo '<input type="text" id="color-'.$args.'" name="bcio_special_options[color_'.$args.']" value="' . $color . '" class="bc-color-field" >';                                    
}

I have tested the solution with per-category color fields. The colors are saved correctly and, if set, display as previously configured.

I hope someone else finds the solution helpful. If I discover any problems, I will post an update to this thread.

Happy coding!

Leave a Comment