Last Updated: February 25, 2016
· rosatimatteo

Linking a Wordpress menu entry to the latest post

Let's suppose you have a Wordpress-generated menu, and you want to link one of the entries to the latest post of your blog.

insert this code in the functions.php file of your theme

// Front end only, don't hack on the settings page
if ( ! is_admin() ) {
    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 )

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

        if ( empty( $latestpost ) )

        // 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;

now be sure to have at least one menu item with a link pointing to "#latestpost": that url will be overwritten by the latter code.

(thanks to Alex