WordPress.org

Make WordPress Core

Opened 3 years ago

Last modified 16 months ago

#21488 reopened enhancement

Add Default Callback Functions for add_settings_field() — at Initial Version

Reported by: mordauk Owned by:
Milestone: Future Release Priority: normal
Severity: normal Version:
Component: Plugins Keywords: has-patch dev-feedback settings-api
Focuses: administration Cc:

Description

By default, when creating options in plugins and themes, every developer is required to create custom callback functions for rendering their option's HTML. The HTML for most options is nothing more than a standard INPUT field, a SELECT field, TEXTAREA field, etc, so there's really no reason there shouldn't be default callback options in place.

For example, if I have a plugin that registers one text field option in the General settings page, it really doesn't make sense that I should be forced to create a callback function, especially not when probably 99% of all text fields are outputted in exactly the same way:

<input name="FIELD NAME" id="FIELD ID" value="FIELD VALUE" class="regular-text"/>
<div class="description">The description of the field (if present)</div>

With default field callbacks available, developers can do this:

function pw_register_settings() {
	register_setting( 'general', 'pw_sample_option', 'esc_attr' );
	add_settings_section( 'pw_sample_section', 'This is a Sample Section', 'pw_sample_section_cb', 'general');
	add_settings_field( 'pw_sample_option', 'A Sample Setting', 'text', 'general', 'pw_sample_section', array( 'description' => 'The field description' ) );
}
add_action('admin_init', 'pw_test_settings');

function pw_sample_section_cb() {
	// this is the section HTML (if you want it)
}

This is much simpler than also having to write the callback function to render the HTML for the option.

The patch attached adds the following default callbacks:

  • text
  • textarea
  • select
  • radio
  • checkbox
  • checkbox_group

For select, radio, and checkbox groups, the options are passed as an array of "choices" in the last, optional $args parameter for add_settings_field():

$options = array( 
	'one' => 'The Choice Name',
	'two' => 'The Second name', 
	'three' => 'The Third option'
);
add_settings_field( 'pw_sample_option', 'A Sample Setting', 'select', 'general', 'pw_sample_section', array( 'choices' => $options, 'description' => 'This is a select' ) );

When a user wants to create a custom callback function, this is still allowed as call_user_func() is the default in the $fieldcallback? switch statement for the do_settings_fields() function.

Change History (1)

@mordauk3 years ago

Adds default callbacks for add_settings_field()

Note: See TracTickets for help on using tickets.