0

Is there anyway you can use a single callback with multiple setting fields? Maybe there is a way to pass the setting field used through the callback?

3

add_settings_field() accepts six arguments, the last one is an array of arguments:

add_settings_field($id, $title, $callback, $page, $section, $args);

You can add custom values here, so you can reuse one callback.

A simple example:

add_settings_field(
    'foo',
    'Foo',
    'wpse_settingsfield_callback',
    'my_page',
    'my_section',
    array ( 'context' => 'foo' ) // custom arguments
);
add_settings_field(
    'bar',
    'Bar',
    'wpse_settingsfield_callback',
    'my_page',
    'my_section',
    array ( 'context' => 'bar' ) // custom arguments
);

function wpse_settingsfield_callback( $args )
{
    if ( 'foo' === $args[ 'context' ] )
        print 'Hello Foo!';
    elseif ( 'bar' === $args[ 'context' ] )
        print 'Hello Bar!';
    else
        print 'Unknown context!';
}

Another option is a separate class for the field rendering. Let’s take a very simple and incomplete class:

class Checkbox_Settingsfield_View {

    protected $attributes, $label;

    public function set_attributes( Array $attributes )
    {
        $this->attributes = $attributes;
    }

    public function render()
    {
        printf(
            '<label for="%1$s"><input type="checkbox"%2$s /></label>',
            $this->attributes[ 'id' ],
            $this->array_to_attrs( $this->attributes )
        );
    }

    protected function array_to_attrs( array $attrs, $xml = TRUE )
    {
        $str = '';

        foreach ( $attrs as $key => $value ) {
            if ( TRUE === $value )
                ( $xml and $value = "='$key'" ) or $value = '';

            $str .= " $key='" . esc_attr( $value) . "'";
        }

        return $str;
    }
}

Now you set up the objects …

$foo_view = new Checkbox_Settingsfield_View;
$foo_view->set_attributes(
    array (
        'name'  => 'foo',
        'style' => 'border:10px solid red'
    )
);
$bar_view = new Checkbox_Settingsfield_View;
$bar_view->set_attributes(
    array (
        'name'  => 'bar',
        'style' => 'border:5px solid blue'
    )
);

… and pass the method render() as callback argument:

add_settings_field(
    'foo',
    'Foo',
    array ( $foo_view, 'render' ),
    'my_page',
    'my_section'
);
add_settings_field(
    'bar',
    'Bar',
    array ( $bar_view, 'render' ),
    'my_page',
    'my_section'
);
  • Is there any way to do this with the sanitize callback? – Andre Yonadam Sep 29 '13 at 14:36
  • @AndreYonadam The sanitize callback gets only one value: the posted values for a form name. But you can use the OOP approach here. – fuxia Sep 29 '13 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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