简体   繁体   中英

Passing argument to function in Wordpress

I have following function:

public function id_callback($idnumber){}

And I call it this way:

for($i = 1; $i <= $fieldcount; $i++)
        {
            add_settings_field(
                'id' . $i, 
                'ID' . $i, 
                array( $this, 'id_callback' ), 
                'my-setting-admin', 
                'setting_section_id'
            );
        }

How can I pass $i as an argument to id_callback ?

Thanks in advance.

Your code is a little abstract, as it does not come with a specific context, however i'll try to help you. You basically have to create a variable and a method that sets that variable. Then you should use that method to change the variable in the for loop. Here is a quick example of what i'm talking about (i've created an example class that replicates a simple use case):

<?php

class Example_Callback {

    public $id_callback;

    public function set_id_callback($id_callback) {
        $this->id_callback = $id_callback;
    }

    public function do_something() {
        // here is your $i:
        $callback_id = $this->id_callback;

        // here you can do something with your $callback_id
    }

    public function test() {
        $fieldcount = 5; // usually this should come from somewhere
        for($i = 1; $i <= $fieldcount; $i++) {

            $this->set_id_callback($i);

            add_settings_field(
                'id' . $i, 
                'ID' . $i, 
                array( $this, 'do_something' ), 
                'my-setting-admin', 
                'setting_section_id'
            );
        }
    }

}

$callback = new Example_Callback();
$callback->test();

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM