Hi there,
I know this is more of a Wordpress related question, but since I don’t have much experience with custom walkers, I thought I would ask it here too;
I would like to automatically add anchor links from a loop in the parent page as a dropdown submenu with a custom menu walker but maintain the nice and clean Roots output.
I use Advanced Custom Fields to add extra content blocks in a page, in each block there is a named anchor that should be added to the parent page as a submenu.
What I changed so far in the display_element
function:
function display_element($element, &$children_elements, $max_depth, $depth = 0, $args, &$output) {
// Add anchors as children elements
if ($depth == 0){
$elementid = $element->ID;
$objectid = $element->object_id;
// Get subitems
$subitems = get_field('sub_items', $objectid);
if ($subitems) {
// Construct child array from anchors
foreach ($subitems as $item) {
$item_title = $item['sub_item_title'];
$item_anchor = sanitize_title($item_title);
// Create new Array for each item
$children_elements[$elementid][] = array(
'post_title' => $item_title,
'post_name' => $item_anchor,
'post_type' => 'nav_menu_item',
'menu_item_parent' => $elementid,
'object' => 'custom',
'type' => 'custom',
'type_label' => 'Anchor',
'title' => $item_title,
'url' => '#'.$item_anchor,
'attr_title' => $item_title
);
}
//print_r($children_elements);
}
}
$element->is_dropdown = ((!empty($children_elements[$element->ID]) && (($depth + 1) < $max_depth || ($max_depth === 0))));
if ($element->is_dropdown) {
$element->classes[] = 'dropdown';
}
parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
}
The normal output of the $children_elements
would be like this:
Array (
[7] => Array (
[0] => WP_Post Object (
[ID] => 124
etc ...
[current_item_parent] =>
)
[1] => WP_Post Object (
[ID] => 125
etc ...
[current_item_parent] =>
)
[2] => WP_Post Object (
[ID] => 126
etc ...
[current_item_parent] =>
)
)
)
But my output of the $children_elements
is like this:
Array (
[7] => Array (
[0] => Array (
[post_title] => 'anchor title'
etc ...
[current_item_parent] =>
)
[1] => Array (
[post_title] => 'anchor title'
etc ...
[current_item_parent] =>
)
[2] => Array (
[post_title] => 'anchor title'
etc ...
[current_item_parent] =>
)
)
)
So the children elements are in an Array and not in a WP_Post Object.
What do I need to change in order to add the anchors correctly without needing to create new nav_menu_item in the database?
Any help is welcome!
Thanks