如何以编程方式将post category明智地添加到wp_nav_menu中?

时间:2016-04-24 09:33:26

标签: wordpress

我想创建一个按类别分类的导航菜单,在每个类别中最新的5个帖子显示。

Cat1 cat2 cat3   | | post1 post2

由于

1 个答案:

答案 0 :(得分:0)

在function.php中 的add_filter( 'wp_get_nav_menu_items', 'display_lasts_ten_posts_for_categories_menu_item',10,3);

function display_lasts_ten_posts_for_categories_menu_item( $items, $menu, $args ) {

$menu_order = count($items);
$child_items = array();

foreach ( $items as $item ) {
if ( 'category' != $item->object || ('category' == $item->object && get_category_children($item->object_id)) )
continue;
$category_ten_last_posts = array(
'numberposts' => 3,
'cat' => $item->object_id,
'orderby' => 'date',
'order' => 'DESC'
);

foreach ( get_posts( $category_ten_last_posts ) as $post ) {
$post->menu_item_parent = $item->ID;
$post->post_type = 'nav_menu_item';
$post->object = 'custom';
$post->type = 'custom';
$post->menu_order = ++$menu_order;
$post->title = $post->post_title;
$post->url = get_permalink( $post->ID );
$child_items[]= $post;
}
}
return array_merge( $items, $child_items );
}
header.php中的

    wp_nav_menu(array('theme_location'=>'primary','menu_class'=>'display_lasts_ten_posts_for_categories_menu_item',));