这是一个呈现两个字段(图像id和url)的动态小部件的示例。如果输入图像id并按“更新”,将添加两个新字段。我构建它是为了创建一个带有图像和链接url的光滑滑子。
<?php
class imp_image_slider extends WP_Widget
{
/**
* imp_image_slider constructor.
*/
public function __construct()
{
parent::__construct(false, $name = "Impulse Image Slider", array("description" => "Creates Slick Image Slider"));
}
/**
* @see WP_Widget::widget
*
* @param array $args
* @param array $instance
*/
public function widget($args, $instance)
{
// render widget in frontend
}
/**
* @see WP_Widget::update
*
* @param array $newInstance
* @param array $oldInstance
*
* @return array
*/
public function update($newInstance, $oldInstance)
{
$instance = $oldInstance;
$instance[\'images\'] = array();
$instance[\'urls\'] = array();
if (isset($newInstance[\'images\'])) {
foreach ($newInstance[\'images\'] as $key => $value) {
if (!empty(trim($value))) {
$instance[\'images\'][$key] = $value;
$instance[\'urls\'][$key] = $newInstance[\'urls\'][$key];
}
}
}
return $instance;
}
/**
* @see WP_Widget::form
*
* @param array $instance
*/
public function form($instance)
{
$images = isset($instance[\'images\']) ? $instance[\'images\'] : array();
$urls = isset($instance[\'urls\']) ? $instance[\'urls\'] : array();
$images[] = \'\';
$form = \'\';
foreach ($images as $idx => $value) {
$image = isset($images[$idx]) ? $images[$idx] : \'\';
$url = isset($urls[$idx]) ? $urls[$idx] : \'\';
$form .= \'<p>\'
. \'<label>Slides:</label>\'
. sprintf(
\'<input type="text" name="%1$s[%2$s]" value="%3$s" class="widefat" placeholder="Image ID">\',
$this->get_field_name(\'images\'),
$idx,
esc_attr($image))
. \'</p>\'
. \'<p>\'
. sprintf(
\'<input type="text" name="%1$s[%2$s]" value="%3$s" class="widefat" placeholder="Url">\',
$this->get_field_name(\'urls\'),
$idx,
esc_attr($url))
. \'</p>\';
}
echo $form;
}
}
add_action(\'widgets_init\', create_function(\'\', \'return register_widget("imp_image_slider");\'));
?>