Skip to content

Instantly share code, notes, and snippets.

@thierrypigot
Last active August 29, 2015 14:25
Show Gist options
  • Save thierrypigot/837941c75ad6e11c294f to your computer and use it in GitHub Desktop.
Save thierrypigot/837941c75ad6e11c294f to your computer and use it in GitHub Desktop.
Allows admin pages containing settings forms to be managed semi-automatically. It lets you define settings pages, sections within those pages and fields within the sections.
<?php
// ------------------------------------------------------------------
// Add all your sections, fields and settings during admin_init
// ------------------------------------------------------------------
//
function tp_settings_api_init()
{
// Add the section to reading settings so we can add our
// fields to it
add_settings_section(
'tp_setting_section',
__('Example settings section in reading'),
'tp_setting_section_callback_function',
'reading'
);
// Add the field with the names and function to use for our new
// settings, put it in our new section
add_settings_field(
'tp_setting_name',
__('Specific pages'),
'tp_setting_callback_function',
'reading',
'tp_setting_section'
);
// Register our setting so that $_POST handling is done for us and
// our callback function just has to echo the <input>
register_setting( 'reading', 'page_contact' );
register_setting( 'reading', 'page_testimonials' );
}
add_action( 'admin_init', 'tp_settings_api_init' );
// ------------------------------------------------------------------
// Settings section callback function
// ------------------------------------------------------------------
//
// This function is needed if we added a new section. This function
// will be run at the start of our section
//
function tp_setting_section_callback_function()
{
echo '<p>'. __('Intro text for our settings section') .'</p>';
}
// ------------------------------------------------------------------
// Callback function for our example setting
// ------------------------------------------------------------------
//
// creates a select page option. Other types are possible ;)
//
function tp_setting_callback_function()
{
?>
<ul>
<li><label for="page_contact"><?php printf( __( 'Contact page: %s' ), wp_dropdown_pages( array( 'name' => 'page_contact', 'echo' => 0, 'show_option_none' => __( '&mdash; Select &mdash;' ), 'option_none_value' => '0', 'selected' => get_option( 'page_contact' ) ) ) ); ?></label></li>
<li><label for="page_testimonials"><?php printf( __( 'Testimonials page: %s' ), wp_dropdown_pages( array( 'name' => 'page_testimonials', 'echo' => 0, 'show_option_none' => __( '&mdash; Select &mdash;' ), 'option_none_value' => '0', 'selected' => get_option( 'page_testimonials' ) ) ) ); ?></label></li>
</ul>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment