我正在为 WordPress 创建一个自定义小部件,但我想使用与默认自定义菜单小部件相同的选择菜单。到目前为止,除了所选菜单之外,我所做的工作没有被保存或显示在前端。对此的任何帮助或指导表示赞赏。谢谢。
为简洁起见,我删除了额外的小部件选项,因此这基本上看起来非常接近自定义菜单小部件:
class kedc_mini_sitemap extends WP_Widget {
/*constructor*/
function kedc_mini_sitemap() {
parent::WP_Widget(false, $name = 'Mini Sitemap');
}
/**/
function widget($args, $instance) {
extract( $args );
// widget options
$title = apply_filters('widget_title', $instance['title']);
$nav_menu1 = ! empty( $instance['nav_menu'] ) ? wp_get_nav_menu_object( $instance['nav_menu'] ) : false;
$checkbox = $instance['checkbox'];
echo $before_widget;
if ($title) {
echo $before_title . $title . $after_title;
}
if ($nav_menu1) {
echo wp_nav_menu( array( 'fallback_cb' => '', 'menu' => $nav_menu1 ) );
}
if ($checkbox == true) {
echo 'This message is displayed if our checkbox is checked.';
}
echo $after_widget;
}
/* saves options chosen from the widgets panel */
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['nav_menu'] = (int) $new_instance['nav_menu'];
$instance['checkbox'] = strip_tags($new_instance['checkbox']);
return $instance;
}
/* display widget in widgets panel */
function form($instance) {
$title = esc_attr($instance['title']);
$nav_menu1 = isset( $instance['nav_menu'] ) ? $instance['nav_menu'] : '';
$checkbox = esc_attr($instance['checkbox']);
$menus1 = get_terms( 'nav_menu', array( 'hide_empty' => false ) );
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget 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 $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('nav_menu'); ?>"><?php _e('Select Menu:'); ?></label>
<select id="<?php echo $this->get_field_id('nav_menu'); ?>" name="<?php echo $this->get_field_name('nav_menu'); ?>">
<?php
foreach ( $menus1 as $menu1 ) {
echo '<option value="' . $menu1->term_id . '"'
. selected( $nav_menu, $menu1->term_id, false )
. '>'. $menu1->name . '</option>';
}
?>
</select>
</p>
<p>
<input id="<?php echo $this->get_field_id('checkbox'); ?>" name="<?php echo $this->get_field_name('checkbox'); ?>" type="checkbox" value="1" <?php checked( '1', $checkbox ); ?>/>
<label for="<?php echo $this->get_field_id('checkbox'); ?>"><?php _e('Do you want this to display as 2 columns?'); ?></label>
</p>
<?php
}
}
// register widget
add_action('widgets_init', create_function('', 'return register_widget("kedc_mini_sitemap");'));