gpt4 book ai didi

php - WordPress Widget API 中的表单归档是否需要 get_field_id()?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:39:15 25 4
gpt4 key购买 nike

我正在尝试为我的插件创建自定义小部件并关注 the codex .

这就是我目前所拥有的。它正在运行并保存并显示保存的选项值。

<?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
}
}

我有两个问题:

  1. 什么是 id="<?php echo $this->get_field_id( 'color' ); ?>"为了?我删除了该行的这一部分,它似乎工作正常。我放置它只是为了复制法典工作代码。
  2. 在构造函数中,第一个参数parent::__construct()是一个基本ID。这可以是任何字符串值吗?我将其从 foo_widget 更改为其他内容它似乎有效。

感谢您提供信息。

最佳答案

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

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

希望对你有帮助!

关于php - WordPress Widget API 中的表单归档是否需要 get_field_id()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12543544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com