You can filter wp_nav_menu_objects
and add a new item. Here is a simple plugin doing that:
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: Latest Post In Menu
* Description: Append a link to the latest post to all nav menus called with the argument <code>'add_latest_post' => TRUE</code>.
* Plugin URI: http://wordpress.stackexchange.com/q/59892/73
* Version: 2012.07
* Author: Thomas Scholz
* Author URI: http://toscho.de
* License: MIT
* License URI: http://www.opensource.org/licenses/mit-license.php
*/
add_filter( 'wp_nav_menu_objects', 'wpse_59892_latest_post_in_nav_menu', 10, 2 );
/**
* Add a link to the latest post to the nav menu.
*
* The nav menu has to be called with 'add_latest_post' => TRUE.
* Example:
* wp_nav_menu(
* array(
* 'theme_location' => 'primary',
* 'add_latest_post' => TRUE
* )
* );
*
* @wp-hook wp_nav_menu_objects
* @param array $sorted_menu_items Existing menu items
* @param object $args Nav menu arguments as object.
* @return array
*/
function wpse_59892_latest_post_in_nav_menu( $sorted_menu_items, $args )
{
if ( ! isset ( $args->add_latest_post ) // argument set?
or ! $args->add_latest_post // argument TRUE?
or ! $latest = get_posts( array ( 'numberposts' => 1 ) ) // post found?
)
{
return $sorted_menu_items;
}
// Uncomment the following line to see what you can change:
// print '<pre>' . htmlspecialchars( var_export( $sorted_menu_items, TRUE ) ) . '</pre>';
$post = $latest[0];
$content = empty ( $post->post_excerpt ) ? $post->post_content : $post->post_excerpt;
$link = array (
'title' => $post->post_title,
'menu_item_parent' => 0,
'ID' => '',
'db_id' => '',
'url' => get_permalink( $post->ID ),
'classes' => array (
0 => '',
1 => 'menu-item',
2 => 'menu-item-type-post_type',
3 => 'menu-item-object-post',
4 => 'latest-post',
),
// strips all tags and reduces the length to 20 words
'attr_title' => wp_trim_words( $content, 20 ),
);
$sorted_menu_items[] = (object) $link;
return $sorted_menu_items;
}
If we write a new post …
… and call the nav menu like this …
wp_nav_menu(
array(
'theme_location' => 'primary',
'add_latest_post' => TRUE
)
);
… we get …
The nav menu item has a class latest-post
, so we can style it per CSS:
.menu .latest-post a
{
color: #eee;
background: #9f0;
}