Add_settings_field() parameterizing callback?

I’m trying to create a rather large and extensive settings page with various options of very similar type.

Since there will be about 20 different fields, and the differences between most of those being simply their ID, I’d like to avoid creating a separate callback for each one.

Read More

Is it possible to make a callback with a variable for the settings ID of each of these fields? That way one callback can server various settings fields of the same type.

I’ve tried using the $args parameter for add_setitngs_feild(), but sadly, it does not work. For example:

add_settings_field('name', 'Field Name', array($this, 'fieldCallback'), 'SettingsGrouP', 'SettingsSection', array("settingID!")); 


function fieldCallback($id)
{
    echo "<input id='" . $id . "'/>";//etc, etc
}

fieldCallback si being called, but the ID of the input is blank.

Related posts

Leave a Reply

4 comments

  1. The last optional $args argument the you can pass to add_settings_fields() is passed to callback. So it seems you can use same callback just fine.

    Hope I am right because I just stumbled onto this two minutes ago because of discussion in chat. 🙂

    PS looked through code and it’s indeed relatively recent, before ~2.9 arguments weren’t passed.

  2. The way WordPress passes arguments to the callback function here is a bit tricky, the callback function receives the whole $args array as parameter, so you may want to change the function as following:

    function fieldCallback(array $args)
    {
        echo "<input id='" . $args[0] . "'/>";//etc, etc
    }
    

    and you leave add_settings_field as it is.

  3. add_settings_field(
        'name', 
        'Field Name', 
        array($this, 'fieldCallback'), 
        'SettingsGrouP', 
        'SettingsSection',
        $args=array("settingID!")
    ); 
    
    function fieldCallback($id) {
       `echo "<input id='" . $id[0] . "'/>";`
    }
    

    OR

    what Jacer Omri illustrated