创建一个新的“自定义链接”菜单项,其中URL为#latestpost(它将充当代码的占位符和目标)。您可以根据自己的喜好为该项目命名。然后,此代码将找到该菜单项(通过查找占位符URL),然后将其URL替换为最新帖子的URL。因为过滤器在添加所选CSS类的代码运行之前,所以菜单高亮显示甚至可以工作。当您访问博客上的最新帖子时,此菜单项将亮起。
将代码放在插件或主题函数中。php文件。
// 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;
}