如何将参数从add_settings_field()传递给回调函数?


16

我有这样的功能:

add_settings_field( 'contact_phone', 'Contact Phone', 'settings_callback', 'general');

这样可行。它调用settings_callback。凉。我遇到的问题是:如果我正在做的事情只是回声一点,我不想为每个添加的设置都定义一个回调函数。

function settings_callback()
{
    echo '<input id="contact_phone" type="text" class="regular-text" name="contact_phone" />';
}

我到底为什么要这样做?id,class和name都应该是params。

没有办法将参数传递给settings_callback函数吗?我开始研究核心,到达这里:http : //core.trac.wordpress.org/browser/tags/3.1.3/wp-admin/includes/template.php

..并进入此$ wp_settings_fields全局字段。在哪里定义?

Answers:


24

查看函数的声明:

function add_settings_field(
    $id,
    $title,
    $callback,
    $page,
    $section = 'default',
    $args    = array()
) { }

最后一个参数接受您的参数,并将其传递给回调函数。

我的插件公开联系数据示例

    foreach ( $this->fields as $type => $desc )
    {
        $handle   = $this->option_name . "_$type";
        $args     = array (
            'label_for' => $handle,
            'type'      => $type
        );
        $callback = array ( $this, 'print_input_field' );

        add_settings_field(
            $handle,
            $desc,
            $callback,
            'general',
            'default',
            $args
        );
    }

该函数print_input_field()将这些参数作为第一个参数:

/**
 * Input fields in 'wp-admin/options-general.php'
 *
 * @see    add_contact_fields()
 * @param  array $args Arguments send by add_contact_fields()
 * @return void
 */
public function print_input_field( array $args )
{
    $type   = $args['type'];
    $id     = $args['label_for'];
    $data   = get_option( $this->option_name, array() );
    $value  = $data[ $type ];

    'email' == $type and '' == $value and $value = $this->admin_mail;
    $value  = esc_attr( $value );
    $name   = $this->option_name . '[' . $type . ']';
    $desc   = $this->get_shortcode_help( $type );

    print "<input type='$type' value='$value' name='$name' id='$id'
        class='regular-text code' /> <span class='description'>$desc</span>";
}

无需触摸全局变量。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.