Allows you to add menu items to the WordPress menu programmatically (dynamically).
<?php
// 1 вариант
add_filter( 'wp_get_nav_menu_items', function ( $items ) {
$locations = get_nav_menu_locations();
if ( ! is_admin() && isset( $locations['main_menu'] ) ) {
$cats = get_categories();
foreach ( $cats as $cat ) {
$item = new WP_Post( new stdClass() );
$item->title = $cat->name;
$item->url = get_category_link( $cat );
$item->db_id = $cat->term_id;
$item->object_id = $cat->term_id;
$item->object = $cat->taxonomy;
$item->type = 'taxonomy';
$item->target = '';
$item->attr_title = '';
$item->description = '';
$item->classes = [];
$item->xfn = '';
$items[] = $item;
$posts = get_posts( [ 'category' => $cat->term_id ] );
foreach ( $posts as $post ) {
$post->url = get_permalink( $post );
$post->title = $post->post_title;
$post->menu_item_parent = $cat->term_id;
$post->object_id = $post->ID;
$post->object = $post->post_type;
$post->type = 'post_type';
$post->target = '';
$post->attr_title = '';
$post->description = '';
$post->classes = [];
$post->xfn = '';
$items[] = $post;
}
}
array_map( function ( $item_menu ) {
static $index = 0;
$item_menu->menu_order = ++ $index;
return $item_menu;
}, $items );
}
return $items;
} );
// Вариант 2
add_filter( 'wp_nav_menu_objects', function ( $items, $args ) {
if ( ! is_admin() && $args->theme_location === 'top' ) {
$cats = get_categories();
foreach ( $cats as $cat ) {
$item = new WP_Post( new stdClass() );
$item->ID = $cat->term_id;
$item->title = $cat->name;
$item->url = get_category_link( $cat );
$item->object_id = $cat->term_id;
$item->object = $cat->taxonomy;
$item->type = 'taxonomy';
$item->target = '';
$item->attr_title = '';
$item->description = '';
$item->classes = [];
$item->xfn = '';
$items[] = $item;
}
_wp_menu_item_classes_by_context( $items );
}
return $items;
}, 10, 2 );