I made my first custom Walker_Nav_menu class and I tried to make it clean as possible. What do you guys think of the functions I made? Please share your versions if possible.
Here is the class
class Walker_Nav_Primary extends \Walker_Nav_menu {
function start_lvl(&$output, $depth = 0, $args = []) {
$output .= '<ul class="dropper--items">';
}
function start_el(&$output, $item, $depth = 0, $args = [], $id = 0) {
$listItem = $this->createListItem($item, $args, $depth);
$link = $this->createLink($item, $args, $depth);
$menuItemOutput = $listItem . $link;
$output .= apply_filters('walker_nav_menu_start_el', $menuItemOutput, $item, $depth, $args);
}
function createListItem($item, $args, $depth) {
$listItemClasses = $item->classes;
$listItemClasses[] = 'menu-item-' . $item->ID;
$listItemClasses[] = $depth ? 'dropper--item' : 'navigation--item';
if ($args->walker->has_children) {
$listItemClasses[] = 'dropper';
}
$listItemClasses = apply_filters('nav_menu_css_class', array_filter($listItemClasses), $item, $args, $depth);
$listItemClassesCombined = implode(' ', $listItemClasses);
$listItemId = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args);
$listItemTag = '<li id="' . $listItemId . '" class="' . $listItemClassesCombined . '">';
return $listItemTag;
}
function createLink($item, $args, $depth) {
$linkAttributes = [];
$linkAttributes['title'] = esc_attr($item->attr_title);
$linkAttributes['target'] = esc_attr($item->target);
$linkAttributes['rel'] = esc_attr($item->xnf);
$linkAttributes['href'] = esc_attr($item->url);
$linkAttributesCombined = '';
foreach ($linkAttributes as $attribute => $attributeValue) {
if (!empty($attributeValue)) {
$linkAttributesCombined .= ' ' . $attribute . '=' . $attributeValue . ' ';
}
}
$linkAttributesCombined .= $depth ? 'class="dropper--link"' : 'class="navigation--link"';
$linkTag = '';
$linkTag .= $args->before;
$linkTag .= '<a' . $linkAttributesCombined . '>';
$linkTag .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$linkTag .= '</a>';
$linkTag .= $args->after;
$linkTag .= $args->walker->has_children ? '<a href="#" class="dropper--toggle">+</a>' : '';
return $linkTag;
}
}