Generating add_settings_section() calls dynamically

I have some pieces of code within functions.php that I could easly replace with much shorter functions, like, for example:

function register_sections() {
   add_settings_section('SOMETHING_settings', 'SOMETHING Settings', 'generate', 'SOMETHING_page' );
   add_settings_section('SOMETHING2_settings', 'SOMETHING2 Settings', 'generate', 'SOMETHING2_page' );
   add_settings_section('SOMETHING3_settings', 'SOMETHING3 Settings', 'generate', 'SOMETHING3_page' );
   add_settings_section('SOMETHING4_settings', 'SOMETHING4 Settings', 'generate', 'SOMETHING4_page' );
(...)
}

add_action('admin_init', 'register_sections');

I guess function replacing the code above will look like:

function settings_sections() {
$array = ('SOMETHING','SOMETHING2','SOMETHING3', 'SOMETHING4');
   foreach($array as $section) {
       echo "add_settings_section('".$section."_settings','".$section." Settings','generate','".$section."_page' ) ;";    
}

But I’m not sure how to initalize this dynamically generated content? Of course add_action('admin_init', 'settings_sections'); echoes function’s output on all admin pages instead of registering sections.

1 Answer
1

Try this instead:

function settings_sections() {
    // array containing settings identifiers
    $array = ( 'SOMETHING', 'SOMETHING2', 'SOMETHING3', 'SOMETHING4' );

    // loop through settings identifiers and generate settings sections
    foreach( $array as $v) {
        add_settings_section(
            $v . '_settings',
            $v . ' Settings',
            'generate',
            $v . '_page'
        );    
    }
}

echo outputs a string, you should just be calling add_settings_section() directly from inside the loop.

Also, NB: generate() is not the best name for a function, you should really go with something that’s less likely to overlap with another function (prefix it with something)

Leave a Comment