0

I am using wp_get_nav_menu_items to display my header menu with the code below

<?php
                $menu_name = 'main-menu';
                $menuitems = wp_get_nav_menu_items($menu_name);
                foreach ($menuitems as $item ) {
                    echo '<a class="dn dib-ns poppins f7 white ml3 ml4-l header-navigation__link-item" href="'.$item->url.'">'.$item->title.'</a>';
                }
            ?> 

I would like to add a class 'active' so I can style it differently from the other menu items when on that specific page.

How can I add a class to active menu item using the wp_get_nav_menu_items?

Thanks

1 Answer 1

0

Hello just posting that I have found a solution for this using

<?php
  $menu_name = 'main-menu';
  $menuitems = wp_get_nav_menu_items($menu_name);
  foreach ($menuitems as $item ) {
    $active_link = ( $item->object_id == get_queried_object_id() ) ? 'current' : '';
    if (!$active_link) {
      echo '<a class="dn dib-ns poppins f7 white hover-gold ml3 ml4-l header-navigation__link-item" href="'.$item->url.'">'.$item->title.'</a>';
    } else {
      echo '<a class="dn dib-ns poppins f7 white ml3 ml4-l header-navigation__link-item active" href="'.$item->url.'">'.$item->title.'</a>';
  }                   
}
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.