Is it possible to add a dynamic link in the main navigation in a child theme

My client would like to have a link to the most recent post in the main navigation, but still be able to manage the navigation through the dashboard as usual. I did not find a plugin that will do this task, so I may need to custom code it. I could add it into the child theme, but I don’t think it would should up in the dashboard menu where they could move it to a different order, if they want.

My searches are not yielding results in either Google or this Community, but I may just not be using the correct search term.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

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

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x