How can the user ensure that the 'class="current-menu-item"' is only applied to the currently active menu item?

To ensure that the 'class="current-menu-item"' is only applied to the currently active menu item, we can check if the current menu item matches the current page or post being viewed. This can be done by comparing the menu item's URL with the current page's URL. If they match, we add the 'class="current-menu-item"' to that menu item.

<?php
$current_url = home_url( $wp->request );
$menu_items = wp_get_nav_menu_items( 'primary' );

foreach ( $menu_items as $menu_item ) {
    if ( $menu_item->url == $current_url ) {
        $menu_item->classes[] = 'current-menu-item';
    }
}
?>