Skip to content

Instantly share code, notes, and snippets.

@ginsterbusch
Created January 28, 2018 04:30
Show Gist options
  • Save ginsterbusch/da942aeb0c736acaebbf39e5bf19db9b to your computer and use it in GitHub Desktop.
Save ginsterbusch/da942aeb0c736acaebbf39e5bf19db9b to your computer and use it in GitHub Desktop.
Custom Nav Menu Walker class which outputs a select dropdown menu with focus on taxonomies instead a regular list-based one.
<?php
if (!class_exists('_my_dropdown_menu_walker')) :
class _my_dropdown_menu_walker extends Walker_Nav_Menu {
// don't output children opening tag (`<ul>`)
function start_lvl( &$output, $depth = 0, $args = array() ) {
}
// don't output children closing tag
function end_lvl( &$output, $depth = 0, $args = array() ) {
}
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
global $wp_query;
$active = '';
if ( $item->current || $item->current_item_ancestor || $item->current_item_parent ) {
$active = 'active';
}
// passed classes
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
// build html
// add product cat as value
$value = '';
if( !empty( $item->type ) && $item->type == 'taxonomy' && !empty( $item->object_id ) ) {
$value = $item->object_id;
}
$href = '';
if( ! empty( $item->url ) ) {
$href = 'data-href="' . esc_attr( $item->url ) . '" ';
}
$output .= $indent . '<option value="'. $value . '" class="' . $class_names . ' ' . $active .'" '.$href.'>';
// add spacing to the title based on the current depth
$item_output = '';
if( $depth > 0 ) {
$item_output .= str_repeat("&nbsp;", $depth * 4);
}
$item_output .= $item->title;
// build html
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
// replace closing </li> with the closing option tag
public function end_el(&$output, $item, $depth = 0, $args = array() ){
$output .= "</option>\n";
}
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment