Hi @ruenel,
Somehow I kept thinking there should be a way to manipulate the default WP menu to achieve this. Long story short: there is!
Turns out the 'wp_get_nav_menu_items' filter is perfect for this, as it let you manipulate the nav-menu, including the items!
Posting the full custom code below. I don’t think any customer should expect customer support to come up with a custom like this. I certainly didn’t. But since I’ve been able to figure it out, I would like to share the code, as it may help others.
Feel free to criticize the code tough, any ideas that might make this code even better I would be happy to incorporate and share here, for others to benefit from!
add_filter('wp_get_nav_menu_items', function ($items, $menu, $args) {
//Dont apply to admin or ajax calls
//if (is_admin() || wp_doing_ajax()) return $items;
if (wp_doing_ajax()) return $items;
//Set allowed taxonomy and post-type
$allowed_taxonomies = ['categorie'];
$post_type = 'aanbod';
$new = [];
$uid = 10000;
//Little helper to count the number of children per parent
$children_count = [];
foreach ($items as $it) {
$pid = (int) $it->menu_item_parent;
if ($pid) {
if (!isset($children_count[$pid])) $children_count[$pid] = 0;
$children_count[$pid]++;
}
}
foreach ($items as $item) {
//Copy existing item values to new var
$new[] = $item;
// Only coninue if item is a taxonomy
if ($item->type !== 'taxonomy') continue;
//Only continue if the taxonomy of this item is one of the 'allowed' list
$taxonomy = $item->object;
if (!in_array($taxonomy, $allowed_taxonomies, true)) continue;
$pid = (int) $item->ID;//Current postID
$term_id = (int) $item->object_id;//Current termID
//Get all posts for the defined post_type that have this term
$q = new WP_Query([
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => true,
'tax_query' => [[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term_id,
'include_children' => false,
]],
'fields' => 'ids',
]);
$post_count = !empty($q->posts) ? count($q->posts) : 0;
//Add all found posts as submenu-items
if (!empty($q->posts)) {
foreach ($q->posts as $post_id) {
$uid++;
$virtual = (object)[
'ID' => $uid,
'db_id' => $uid,
'menu_item_parent' => $pid,
'object_id' => (string) $post_id,
'object' => $post_type,
'type' => 'post_type',
'type_label' => 'Post',
'title' => get_the_title($post_id),
'url' => get_permalink($post_id),
'classes' => ['menu-item-object-'.$post_type],
'status' => 'publish',
'menu_order' => $uid,
];
$new[] = wp_setup_nav_menu_item($virtual);
}
}
}
return $new;
}, 999, 3);