Skip to content

Instantly share code, notes, and snippets.

@moabi
Created June 11, 2015 15:01
Show Gist options
  • Save moabi/9a88c675e5dd67144d54 to your computer and use it in GitHub Desktop.
Save moabi/9a88c675e5dd67144d54 to your computer and use it in GitHub Desktop.
retrieve a menu and format it
/**
* MENU widget
*
*/
class menu_widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'menu-widget', // Base ID
__( 'Lyra Network - menu widget', 'twentyfifteen' ), // Name
array( 'description' => __( 'add a menu in the sidebar', 'twentyfifteen' ), ) // Args
);
}
/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
echo $args['before_widget'];
if ( ! empty( $instance['menu'] ) ) {
wp_nav_menu( array(
'menu_class' => 'sidebar-nav-menu',
'menu' => $instance['menu'],
'menu_id' => $instance['menu'].'sidebar',
'menu_class' => 'side-menu',
'container' => false,
'depth' => 1,
) );
}
echo $args['after_widget'];
}
/**
* Back-end widget form.
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
public function form( $instance ) {
$menu = ! empty( $instance['menu'] ) ? $instance['menu'] : 'main_menu';
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Please pick a menu:' ); ?></label>
<?php
$args = array(
'public' => true,
);
$post_types = get_post_types( $args, 'names','and' );
$menus = get_terms( 'nav_menu', array( 'hide_empty' => true ) );
echo '<select class="widefat" id="'.$this->get_field_id('menu').'" name="'.$this->get_field_name('menu').' " type="text">';
foreach ( $menus as $menuObj ) {
$sel = ( $menuObj->name == $menu ) ? 'selected' : '';
echo '<option '.$sel.' value="' . $menuObj->name . '" >' . $menuObj->name . '</option>';
}
echo '</select>';
?>
</p>
<?php
}
/**
* Sanitize widget form values as they are saved.
*
* @see WP_Widget::update()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
*
* @return array Updated safe values to be saved.
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['menu'] = ( ! empty( $new_instance['menu'] ) ) ? strip_tags( $new_instance['menu'] ) : '';
return $instance;
}
} // class Foo_Widget
// register Foo_Widget widget
function register_menu_widget() {
register_widget( 'menu_widget' );
}
add_action( 'widgets_init', 'register_menu_widget' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment