zeshan-a
9/2/2018 - 11:58 AM

Custom WP Nav Walker

Custom WP Nav Walker class.

<?php

if ( class_exists( 'Rarus_Nav_Walker' ) ):

  class Rarus_Nav_Walker extends Walker_Nav_Menu {

    private $cur_item;

    /**
     * Start Level
     */
    function start_lvl( &$output, $depth = 0, $args = array() ) {

      $indent = str_repeat("\t", $depth);

      $dropdown_class = 'sub-menu';

      if ( in_array( 'mega-menu', $this->cur_item->classes ) ) {
        $dropdown_class = 'mega-menu__ul';
        $output .= "\n$indent<div class=\"mega-menu__inner\"><div class=\"mega-menu__inner2\"><ul role=\"menu\" class=\" $dropdown_class\">\n";
      } else {
        $output .= "\n$indent<ul role=\"menu\" class=\" $dropdown_class\">\n";
      }
    }

    /**
     * Start Element
     */
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

      // Current Item.
      $this->cur_item = $item;

      $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

      // ACF Fields
      $hide_title = false;
      if ( function_exists( 'get_field' ) ) {
        $hide_title = get_field( '_hide_menu_title', $item );
      }

      // Classes
      $class_names = $value = '';
      $classes = empty( $item->classes ) ? array() : (array) $item->classes;

      if ( $hide_title ) {
        $classes[] = 'hide-title';
      }

      $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
      $class_names = ' class="' . esc_attr( $class_names ) . '"';

      // Output
      $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';

      // Link Attributes
      $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
      $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
      $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
      $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';

      $item_output = $args->before;

      // Link
      $item_output .= '<a'. $attributes .'><span>';
      $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
      $item_output .= '</span></a>';

      // Description
      $item_output .= ( $item->description ) ? '<div class="mega-menu__item-description">' . do_shortcode( $item->description ) . '</div>' : '';

      $item_output .= $args->after;

      $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }

    /**
     * End Level
     */
    function end_lvl( &$output, $depth = 0, $args = array() ) {

      $indent = str_repeat("\t", $depth);

      if ( in_array( 'mega-menu', $this->cur_item->classes ) ) {
        $output .= "$indent</ul></div></div>\n";
      } else {
        $output .= "$indent</ul>\n";
      }
    }
  }

endif;