WordPress – Replace Menu Item Link

In some cases, it is helpful to change the link in the menu on some different pages. Imagine you have a landing page specific for one of your services or products and you want to have a different contact page for each one. Instead of overwriting the menu for each page, you could just overwrite one menu link. Here is how I did it.

Before you’d need to store a custom field for this page. Then you can access it with get_post_meta.

Then I’ve matched based on another value that you decide in a custom field as well. Which is the title of the menu item that I want to replace for this page. The $item variable actually contains a typical post object.

get_post_meta(get_the_ID(), 'custom_login', true);


function wpse31748_exclude_menu_items( $items, $menu, $args ) {
	// Iterate over the items to search and destroy
	$id = get_the_ID();
	$mo = get_post_meta($id, 'menu_overwrite', true);
	$cl = get_post_meta($id, 'custom_login', true);
	$mo = strtolower($mo);

	foreach ( $items as $key => $item ) {
		if ( strtolower($item->post_title) == $mo )
			if( $cl )
				$items[$key]->url = $cl;
	}

	return $items;
}

Credit due for soulseekah
https://wordpress.stackexchange.com/questions/31748/dynamically-exclude-menu-items-from-wp-nav-menu

Leave a Reply