您可以筛选wp_nav_menu_objects
并添加新项目。下面是一个简单的插件:
<?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;
}
如果我们写一篇新文章…
…然后像这样调用导航菜单…
wp_nav_menu(
array(
\'theme_location\' => \'primary\',
\'add_latest_post\' => TRUE
)
);
…我们得到…
导航菜单项有一个类latest-post
, 因此,我们可以根据CSS设置样式:
.menu .latest-post a
{
color: #eee;
background: #9f0;
}