Code Snippet: Add A Link To Latest Post To WordPress Nav Menu

Someone on #wordpress IRC support channel was trying to add link to their latest blog post to their WordPress navigation menu, so I threw together a few lines of code to help them accomplish this.

// Front end only, don't hack on the settings page
if ( ! is_admin() ) {
	// Hook in early to modify the menu
	// This is before the CSS "selected" classes are calculated
	add_filter( 'wp_get_nav_menu_items', 'replace_placeholder_nav_menu_item_with_latest_post', 10, 3 );
}

// Replaces a custom URL placeholder with the URL to the latest post
function replace_placeholder_nav_menu_item_with_latest_post( $items, $menu, $args ) {

	// Loop through the menu items looking for placeholder(s)
	foreach ( $items as $item ) {

		// Is this the placeholder we're looking for?
		if ( '#latestpost' != $item->url )
			continue;

		// Get the latest post
		$latestpost = get_posts( array(
			'numberposts' => 1,
		) );

		if ( empty( $latestpost ) )
			continue;

		// Replace the placeholder with the real URL
		$item->url = get_permalink( $latestpost[0]->ID );
	}

	// Return the modified (or maybe unmodified) menu items array
	return $items;
}

Place the above code in a plugin or just in your theme’s functions.php file.

Create a new “Custom Link” menu item where the URL is #latestpost (which will act as a placeholder and target for the code). You can title the item whatever you please. This code will then find that menu item (by looking for the placeholder URL) and then replace it’s URL with that of the latest post’s URL. Since the filter is before the code that adds the selected CSS classes runs, the menu highlighting will even work. When you visit the latest post on your blog, this menu item will light up.

Rather simple and elegant. You gotta love WordPress hooks.

89 thoughts on “Code Snippet: Add A Link To Latest Post To WordPress Nav Menu

  1. I’ve read almost all comments since 2012 but can’t find a solution to my problem. The code has worked perfect for me, Thanks for that! Only problem is I would like to use the latest post as my homepage. I have it in the navigation nav now (‘Accueil’) but I would like to set it as my main homepage. I am sorry to bother you… It’s obviously not your problem but it’s for a charity website. Thanks!

  2. I am really sorry I just read the article about Alex after posting my reply. Please apologise and ignore my comment. My condolences to his family. It looks like Alex has contributed a lot to the world. Love, Caroline

Comments are closed.