Single callback with multiple setting fields

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'
);

Leave a Comment