I would like to customize the nav menu walker so that when it encounters a category it automatically makes the 5 most resent posts children of the menu item. Is there a way to dynamically add items to the menu object or it better to have a conditional in the start_el function?

  • start_el-- aka, extend the walker.
    – s_ha_dum
    Mar 31 '14 at 21:18

You could either extend the Walker_Nav_Menu walker class (i.e., the start_el function is sufficient, as already mentioned).
Or you could hook in when the original output (i.e., the category) has been created. That would be the walker_nav_menu_start_el hook.

For instance like so:

function wpdev_139801_start_el( $item_output, $item ) {
    if ( isset( $item->object ) && $item->object === 'category' ) {
        // Set up your query here,
        // then concatenate the output to $item_output
        // You could do this using wp_get_archives()

    return $item_output;
} // function wpdev_139801_start_el

add_filter( 'walker_nav_menu_start_el', 'wpdev_139801_start_el', 10, 2 );
  • This will add the posts in a list if I choose but will not put the posts threw the walker. Therefore the posts will not have the same classes that the Walker_nav_menu puts on the elements by default. Will I just have to manually add those classes in the wpdev_139801_start_el function after my query when contructing my ouput?
    – jppower175
    Mar 31 '14 at 22:41
  • Ah, okay, now I see what you are trying to do. I didn't think about actually including the category posts into the walker output. To do so, you might want to use some other hook, and adjust the actual objects for the walker function. Have a look at the wp_get_nav_menu_items hook.
    – tfrommen
    Mar 31 '14 at 22:46
  • I was looking at the nav menu object itself. Dynamically creating objects and inserting them was kind of what I was think but didn't know if that was possible. Specifically because the dynamically created item would not have an Object ID that corresponded to anything with a nav_menu taxonomy.
    – jppower175
    Mar 31 '14 at 22:58
  • Well, yes, if you add your 5 (or so) posts to the nav menu items they won't have an item ID (in terms of the CSS class). But all the other (relevant) classes can/will be generated without a problem.
    – tfrommen
    Mar 31 '14 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.