Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
1  
Interestingly, I've already linked (and copy-pasted) functioning code for this exact implementation, in your other question. I do basically exactly what @m0r7if3r used in his answer. –  Chip Bennett Feb 10 '12 at 17:13
add comment

1 Answer

up vote 8 down vote accepted

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)

share|improve this answer
    
Exactly right. Also: I'd give another +1 if I could, for the comment about proper function namespacing. A good practice is always to prefix anything in the public namespace, with theme-slug (or plugin-slug, as appropriate). –  Chip Bennett Feb 10 '12 at 17:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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