get_field_id()是否需要WordPress Widget API中的表单?

Ten*_*eno 5 php wordpress wordpress-theming wordpress-plugin

我正在尝试为我的插件创建一个自定义小部件并遵循该手抄本.

这就是我到目前为止所拥有的.它正在工作并保存并显示保存的选项值.

<?php
/**
 * Plugin Name: Sample Widget
 */

$colors = array('red', 'blue', 'yellow');
update_option('sample_widget', $colors);

add_action( 'widgets_init', create_function( '', 'register_widget( "Sample_Widget" );' ) );
class Sample_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'foo_widget', 
            'Sample Widget', 
            array( 'description' => __( 'This is a description of the sample widget', 'text_domain' ), ) // Args
        );
    }

    public function widget( $args, $instance ) {
        extract( $args );
        $title = apply_filters( 'widget_title', $instance['title'] );
        $color = apply_filters( 'widget_title', $instance['color'] );

        echo $before_widget;
        if ( ! empty( $title ) )
            echo $before_title . $title . $after_title;
        echo 'the selected color is ' . $color . '<br />';
        echo $after_widget;
    }

    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = strip_tags( $new_instance['title'] );
        $instance['color'] = $new_instance['color'];
        return $instance;
    }

    public function form( $instance ) {
        if ( isset( $instance[ 'title' ] ) ) {
            $title = $instance[ 'title' ];
        }
        else {
            $title = __( 'New title', 'text_domain' );
        }
        if ( isset( $instance[ 'color' ] ) ) {
            $selected_color = $instance[ 'color' ];
        }
        $colors = get_option('sample_widget');
        ?>
        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
            <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
        </p>
        <p>
            <select name="<?php echo $this->get_field_name( 'color' ); ?>" id="<?php echo $this->get_field_id( 'color' ); ?>">
                <option value="">Select...</option>
                <?php foreach($colors as $color) echo '<option value="' . esc_attr( $color ) . '" ' . ($color == $selected_color ? 'selected="Selected"' : '') .  '>'. $color .'</option>'; ?>
            </select>
        </p>
        <?php 
    }
} 
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. 什么是id="<?php echo $this->get_field_id( 'color' ); ?>"?我删除了这部分线,似乎工作正常.我把它放在只是复制codex工作代码.
  2. 在构造函数中,第一个参数parent::__construct()是基本ID.这可能是任何字符串值吗?我把它改成别的东西,foo_widget似乎工作.

感谢您的信息.

Ner*_*oor 4

  1. id="<?php echo $this->get_field_id( 'color' ); ?>"是为此选项生成唯一的“id”值。通常这样可以通过 JS 操作该对象。

  2. ofid_basefoo_widget该类型所有小部件的根 ID。它是小部件的可选基本 ID,小写,如果留空,将使用小部件类名的一部分。它必须是独一无二的。这将附加到各个小部件的 ID 号,即foo_widget-001

希望这对您有帮助!