How to add custom link to menu in wordpress programmatically?

You must return the value of a filter instead of echoing it…

Example:

add_filter('wp_nav_menu_items', function($items, $args) {

        $link = '<li>Login</li>';

        return $items . $link;

}, 20, 2);

The above will effect all menus however, instead use the $args variable to conditionally modify a specific menu only or use "wp_nav_menu_{$menu->slug}_items" which will only operatae on a specific menu, where $menu->slug is the key value passed to register_nav_menus or register_nav_menu

Recommended reading: