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.
Nice work Alex. Is it possible to just change line 20 to get a drop-down menu with multiple recent posts?
Adding menu items gets significantly more complicated. See the source of my Add Descendants As Submenu Items as an example.
An easier solution would be to just create more placeholders and have the code snippet handle those too, such as
#latestpost1,#latestpost2, etc.how can i use it for another menu item to a different category?
I have been looking for something similar to this, but how can I display last post’s title on the menu ?
First off, this is a fantastic snippet. Thanks for putting it out there.
Question: Is it possible to confine this snippet to drawing posts from a particular category?
Yes! See this snippet from the code?
// Get the latest post $latestpost = get_posts( array( 'numberposts' => 1, ) );Just add the category in there, like so:
// Get the latest post $latestpost = get_posts( array( 'numberposts' => 1, 'category' => 123, ) );Hope that helps! =)
Oops, I somehow overlooked Bri Bri’s comment. Thanks for the reply.
I also made a small fix to your code (wrong parameter name).
Duh copypasta! Thanks, Alex. And thanks for making it all code-pretty, too.
Finding this post helped me out, so helping someone else out (or, well, trying to) was the least I could do. =)
Hi, thanks, the code is working. Is there also a way to retrieve also the name of the post in the menu label?
After this:
Add this:
Thank you!!! Works like a charm!
Code worked perfect the first time in my menu. Thanks!
Is there a way to use this code to make a link from a button on a page to the most recent category? (Same way it does from the menu) I have been beating my head on my desk trying to figure out a solution on this one…
“A button on a page”? Such as in the content of the page? Sounds like you want a shortcode for that.
add_shortcode( 'latestposturl', 'shortcode_latestposturl' ); function shortcode_latestposturl() { // Get the latest post $latestpost = get_posts( array( 'numberposts' => 1, ) ); if ( empty( $latestpost ) ) return '#'; return get_permalink( $latestpost[0]->ID ); }Thanks for this snipped Alex. works great on the menu.
I’m trying to redirect from the footer links (on a template) to the most recent post of a category, and the previous shortcodes doesn’t work unless it’s in a content page.
Any idea how to get that working?
Thanks for your time.
Alex
its working for me
Thank you so much!
what if i want to use it for another menu item for a different category?
What do you mean “a different category”? Show the latest post in a particular category? You’ll want extra placeholders or something along those lines.
I use your code for “Custom Link” menu item that links with the placeholder to last post of category id 4. And it’s working fine: (part of the code)
if ( ‘#latestpost’ != $item->url )
continue;
// Get the latest post
$latestpost = get_posts( array(
‘numberposts’ => 1,
‘category’ => 4,
) );
What I need is to use another “Custom Link” menu item, That will link to the latest post in category id 5.
What is the complete code for doing this?
This is what I sent him via e-mail: https://gist.github.com/2638975
This code is fantastic- what I’d like to know is how to have the 5 latest blog posts instead of just the first. Is that possible?
Well a menu item can only have a single link.
The easiest solution would be something like this: https://gist.github.com/2638975
But instead of setting
$args['category']instead set$args['offset']to varying numbers to get the correct post for each placeholder.Thanks Viper, this helped me solve something that I could not fix with a plugin…
For anyone looking to do this with a custom post type, here’s the part of the code that you need to edit (add the ‘post_type” line):
$latestpost = get_posts( array(
‘numberposts’ => 1,
‘post_type’ => ‘your_post_type_here’,
) );
And to lookup all the other arguments that you can pass into the get_posts function, see:
http://codex.wordpress.org/Function_Reference/get_post
Thank you! very very helpful!
Hello. Thanks for the helpful code. I modified it slightly as suggested in the comments to return the latest 5 entries along with their titles. I would like to truncate long titles though so it works better in my menu. I have tried unsuccessful to modify the script to do so usually other tutorials a reference but it’s clear I don’t really know what I’m doing. Can someone help me out? Here’s what I have
Replace this line:
With this:
That will cut off the title before the first space found after the first 35 characters are skipped.
Thanks for the quick reply. For some reason I was getting an offset error so I just simplified it to
Would be nice to add a “…” at the end but I don’t want to get too complicated with ifs. Thanks
Would only want it to add the “…” if it actually did trim the post title down and not for every post title. Thanks.
Code works great, but its just a plain page. How can I get the widgets to show on the latests post page
Sweet! thanks!
Hi Alex, I am trying to put together something similar, I need a menu item that dynamically links to the most recently added category of a custom taxonomy. Any ideas on how to pull that into the loop?
Thanks, worked like a charm!
Thanks a lot for this!
Hi Trixi, I could manage to do it with a plugin called “Blog in Blog”. It’s pretty straight forward:
As the documentation explains, use a shortcode in your page (mine e.g = [blog_in_blog category_slug='brands+case-studies' num=1 pagination=off] ). This calls the category brands and case studies and shows one post without pagination. Simply add the page ID to your menu.
Hope this helps!
Alex
Hi
Love this, used it to create a login / logout link for WooCommerce https://gist.github.com/3596494
Thanks
This saved my bacon. Thanks Alex!
Thanks Alex, this code helped me a lot!
Now I want to have multiple menu items, all pointing to the latest posts within different categories. How do I duplicate this code in functions.php.
I want a button for the category ‘Life’, and for ‘Sketches’, and from what I’ve understood, I use ‘category’ => Life,
But do I duplicate the whole snippet of code multiple times for each category, or is there a better way of doing it?
Regards,
Øystein