How can one utilize a variable as a callback function name for add_settings_field

I’m trying to cut down on the amount of code that is in my theme options function. I’m adding my settings like so: add_settings_field($k,$v,$callback,$the_options,$the_group,$args);

This works for me in every way as long as I write out the name of the function. For example, if $callback = ‘awesome_callback’ – and I create a function called

Read More
awesome_callback(){ echo 'something'}; 

there are no issues whatsoever.

The following loop also works and loops through the array of options to create the settings fields.. and grabs all the necessary data. it also echoes out exactly what I think my callback should be named. However, right now i have a gagillion callback functions outside of this loop that all look exactly the same except for the name of the function. 🙁

foreach($theOptions as $k=>$v) {

    add_settings_field($k,$v,$callback,$the_options,$the_group,$args);
    echo $callback;

}

Bare with me. I hope someone has faced this issue before and will let me know I’m missing something obvious. The following also works within my wordpress environment outside of the same loop.

$callback = 'awesome_callback';
$callback = function() {
    echo 'awesome callback';
}
$callback();

However, the following returns an error to unknown callback function even though when I echo out the $callback variable, it echoes out the exact string I am referencing in the callback function. I guess I am over-riding the callback value… ???

foreach($theOptions as $k=>$v) {

    $callback = $k.'_callback';
    add_settings_field($k,$v,$callback,$the_options,$the_group,$args);


    $callback = function() {
        echo 'Testing the callback !!! <br>';
    };

}

Can anyone explain a solution for looping through an array of options in a way that will allow to call the callback function within the loop, without having to hard-code it? Is this something that could be solved using a class? I can’t squeeze my head around it.

Related posts

Leave a Reply

1 comment

  1. Do not use different callbacks, use the the sixth parameter for add_settings_field() instead. That is an array, and you can pass any data to the callback here.

    Example:

    foreach( $theOptions as $k => $v ) 
    {
        add_settings_field(
            $k,
            $v,
            'my_callback',
            $the_options,
            $the_group,
            array (
                'special' => $k
            )
        );
    }
    
    function my_callback( $args )
    {
        var_dump( $args['special'] );
    
        switch ( $args['special'] )
        {
            case 'foo':
                // do something
                break;
            case 'bar':
                // do something else
                break;
            default:
                // default handler 
        }
    }