問題描述

我有一個這樣的功能:

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 全局。這個定義在哪裏?

最佳解決方案

看看函數的聲明:

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

最後一個參數需要你的參數並將它們傳遞給回調函數。

示例從我的插件 Public Contact Data

    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>";
}

無需觸摸全局變量。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。