如果我理解正确,您希望最新帖子作为子菜单项出现在菜单中,对吗?类似这样:
Category One top menu item
| Post A sub menu item
| Post B sub menu item
我发现此解决方案发布在此处:
https://alex.blog/2011/09/20/code-snippet-add-a-link-to-latest-post-to-wordpress-nav-menu/, 并将其更改为不仅替换菜单项的URL,还替换标题:
// 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 );
// And also replace the title
$item->title = $latestpost[0]->post_title;
}
// Return the modified (or maybe unmodified) menu items array
return $items;
}
只需遍历所有占位符即可
#latestpost1
,
#latestpost2
, 等等,还有变化
$latestpost
获取类别的最后一个、倒数第二个、倒数第三个。