No Sketchbook Sunday this week as I’ve been busy coding some new tools to help speed up my WordPress development.
I’ve been developing a class-based Base Plugin environment that allows me to quickly create new settings pages (on both themes and plugins) and focus on form creating, validation and program logic (I can’t wait until PHP5.3 is more widespread. So many times I could have used Late Static Bindings and proper Namespacing…)
I’ve been using the Settings API but I also wanted to be able to switch between Tabs, Meta boxes and vanilla HTML simply by changing one class variable.
In order for this to work, I needed more control over how the Settings are displayed. The default WordPress function is the do_settings_sections(); but this simply dumps out all of the sections in one go—no good if you’re trying to separate out individual sections on one page in order to use JavaScript-based tabs or individual Meta Boxes.
Digging through the core, I had a look over the Settings API functions. The do_settings_sections(); is actually pretty straightforward. It basically just loops through a huge array of all of the pre-defined section areas. So I adapted it and came up with this single version:
if ( !function_exists('line_in_do_settings_section') ) {
function line_in_do_settings_section($page, $section) {
global $wp_settings_sections, $wp_settings_fields;
if ( !isset($wp_settings_sections) || !isset($wp_settings_sections[$page]) )
return;
echo "<h3>{$wp_settings_sections[$page][$section]['title']}</h3>\n";
call_user_func($wp_settings_sections[$page][$section]['callback'], $wp_settings_sections[$page][$section]);
if ( !isset($wp_settings_fields) ||
!isset($wp_settings_fields[$page]) ||
!isset($wp_settings_fields[$page][$wp_settings_sections[$page][$section]['id']]) )
return;
echo '<table class="form-table">';
do_settings_fields($page, $wp_settings_sections[$page][$section]['id']);
echo '</table>';
}
}
Now all I need to do is pass the $page and $section that I want to display, and it’ll only display that section. With this level of control, it’s trivial to set up a looping system (for example with tabs):
<?php
// A bunch of pre-defined setting section ids
$tabs = array(
'default-settings',
'advanced-settings'
);
<div class='wrap line-in-plugin'>
<?php screen_icon( 'plugin' ); ?>
<h2 class='lif-title'>
<span><?php _e( 'My Example Plugin', $this->lang ); ?></span>
<?php
$i = 1;
foreach ( $tabs as $tab ) { ?>
<a class="nav-tab hidden" href='#tab-<?php echo $i; ?>'><?php _e( 'Tab ' . $i, $this->lang ); ?></a>
<?php
$i++;
} ?>
</h2>
<form action="options.php" method="post">
<?php $this->settings->get_settings_fields('my-settings-page'); ?>
<?php
$i = 1;
foreach ( $tabs as $tab ) { ?>
<div id='tab-<?php echo $i; ?>' class='lif-tab'>
<?php line_in_do_settings_section('my-settings-page', $tab); ?>
</div>
<?php
$i++;
} ?>
<p class='submit'>
<?php submit_button(); ?>
</p>
</form>
</div>
Instant tabbed settings pages!







