我想在主菜单上的父类别下添加10个最近的帖子

时间:2020-09-15 作者:Jack

我的导航菜单中有两个父类别作为单独的博客页面。我想在同一菜单下显示每个类别的10篇最新帖子。我一直在寻找,但什么也找不到。有人知道怎么做吗?

谢谢

1 个回复
SO网友:botondcs

如果我理解正确,您希望最新帖子作为子菜单项出现在菜单中,对吗?类似这样:

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 获取类别的最后一个、倒数第二个、倒数第三个。

相关推荐

How to list posts by terms

我有一个带有自定义分类法和3个不同术语的自定义帖子类型。我正在尝试构建具有以下结构的页面:Term 1<贴子标记为术语1Term 2<用术语2标记的帖子Term 3<贴有术语3等的帖子。。。实现这一目标的最佳方式是什么?是否有\\u term()?