php - highlight a wordpress nav link for a single page

I have an archive events page that links to a single page that lists all previous events created in the past and can only be visited via the archive events page.

My question is, how can I highlight the archive events page url link when viewing this single page?

For example the below snippet targets a hard-coded nav link to highlight the events link when viewing the other page, however my menu is not hard-coded:

<nav class="main-navigation">
  <ul>
    <li>...</li>
    <li>...</li>
    <li> 
      <?php if(get_post_type() == 'event' OR is_page('past-events')) echo 'class="current-menu-item"';?>>
      <a href="<?php echo get_post_type_archive_link('event'); ?>">events</a>
    </li>
    <li>...</li>
  </ul>
</nav>

The tutorial I am following does not give the alternative coded way of targeting this similarly in the functions.php page, for a dynamic menu that is created via the wordpress dashboard menu.

I have tried searching for examples, but I havent found anything that has helped so far and in need of some outside help.

How can I do this?

Answer

Solution:

I can see something wrong. you haven't put the php code in right place. corrected code is this. try this and let me know if it works

<nav class="main-navigation">
  <ul>
    <li>...</li>
    <li>...</li>
    <li <?php if(get_post_type() == 'event') echo 'class="current-menu-item"';?>> 
      <a href=""<?php echo get_post_type_archive_link('event'); ?>"></a>
    </li>
    <li>...</li>
  </ul>
</nav>

Answer

Solution:

Ok, I think I have found a solution -- being a novice -- has worked!

Hopefully someone can point out any changes/improvements I could make, but here it is:

To highlight a menu link for a different page than the one that you are on/viewing, for example in my scenario: I have an archive events page and within that page I have a link that takes you to a single page that lists all past previous events, but that has no link in the main navigation to it.

function nav_class($classes) {
    // Remove "current-menu-item" class
    $classes = array_diff($classes, array('current-menu-item'));

    // If this is the "past-events" page, highlight the event menu item
    if (in_array('menu-item-36', $classes) && is_page('past-events')) {
        $classes[] = "current-menu-item";
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'nav_class', 10, 2);

I hope this helps someone else out.

Source