Conditionally insert content in wp_nav_menu using custom walker
-
I am trying to dynamically add a nested ul to a list item in a wp nav menu when the walker encounters its own item $id that matches an id passed to the walker.
I created a custom walker which is required by my functions.php file. I am calling the walker inside of a sidebar script in its own sidebar.php file. My sidebar.php has this code:
if(is_singular('event')) { $event= em_get_event($id,'post_id'); echo 'single' .$event->post_id; global $post; if($post->ID == $event->post_id) echo 'a match!'; if(in_array($post->ID, $em_past_exhibit_post_ids)) { $nav_id = 117; } else if(in_array($post->ID, $em_current_exhibit_post_ids)) { $nav_id = 115; } else if(in_array($post->ID, $em_future_exhibit_post_ids)) { $nav_id = 224; } else if(in_array($post->ID, $em_past_concert_post_ids)) { $nav_id = 562; } else if(in_array($post->ID, $em_current_concert_post_ids)) { $nav_id = 558; } else if(in_array($post->ID, $em_future_concert_post_ids)) { $nav_id = 560; } else { $nav_id = 61; } $ptitle = get_the_title( $nav_id ); $plink = get_the_permalink( $nav_id ); echo 'nav id is: ' . $nav_id; $defaults = array( 'theme_location' => 'my-header-menu', 'menu' => '', 'container' => '', 'container_class' => '', 'container_id' => '', 'menu_class' => '', 'menu_id' => 'my-events', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3, 'walker' => new my_event_walker, 'walker_nav_id' => '61', 'walker_el_name' => 'test' ); function modify_nav_menu_args( $args ) { if( 'my-header-menu' == $args['theme_location'] ) { global $post; $id = $post->ID; $args['link_after'] = 'id is:' . $id; } return $args; } add_filter( 'wp_nav_menu_args', 'modify_nav_menu_args' ); wp_nav_menu( $defaults );
In my actual walker, in the start_el function, where output is structured, I thought I could add (at approx. line 141 of just the Walker Nav Menu class ) `$item_output = $args->before;
$item_output .= ‘<a’. $attributes .’>’;
/** This filter is documented in wp-includes/post-template.php */
$item_output .= $args->link_before . apply_filters( ‘the_title’, $item->title, $item->ID ).$args->link_after;if($item->ID = $args->walker_nav_id) {
$item_output .= ‘<ul><li>’ . $args->walker_el_name. ‘</li></ul>’;
}
$item_output .= ‘</a>’;$item_output .= $args->after;
`
the site is only local right now. But I’m wondering how I would a. pass the $nav_id to the walker class and b. how and where I would access the item ids that walker is ‘walking’ to create the menu so that I can compare the two. Do I need to pass that as an argument to link_after or shouldn’t I be able to modify the walker directly? Thank you for your thoughts.
- The topic ‘Conditionally insert content in wp_nav_menu using custom walker’ is closed to new replies.