Creating Reusable Controls with the Settings API

Here’s a tip! add_settings_field() has an $args parameter which is an array, passed on to the callback functions that you assign. So it’s pretty easy to create reusable controls, like this:

/**
 * Text Field
 *
 * A simple text field callback to use with the Settings API. Don't forget to pass in
 * the arguments array. Here's an example call to add_settings_field() :
 *
 * add_settings_field( 'my_option', __( 'My Option' ), 'foo_field_text', 'theme_options', 'general', array(
 *     'name' => 'my_theme_options[my_option]',
 *     'value' => $options['my_option'], // assuming $options is declared
 *     'description' => __( 'Write some description for the field here.' ),
 * ) );
 */
function foo_field_text( $args ) {
    extract( wp_parse_args( $args, array(
        'name' => null,
        'value' => null,
        'description' => null,
    ) ) );
    ?>
    <input type="text" name="<?php esc_attr_e( $name ); ?>" value="<?php esc_attr_e( $value ); ?>" />
    <?php if ( $description ) : ?><span class="description"><?php echo $description; ?></span><?php endif; ?>
    <?php
}

Obviously you can add as many arguments as you like and whatever other customization you need. You can then reuse these controls in the same theme, or in your next one! So if you still think the Settings API should come with a bunch of standard controls you can use, (IMO) think again :)

6 thoughts on “Creating Reusable Controls with the Settings API

  1. Pingback: Options Framework Theme | Theme Options Gallery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s