Add a specific category at a specific place to the menu that uses wp_list_pages

I have a main menu where I display pages. All the pages have associated sub-pages, however in the menu some of them are displayed by themselves without sub-pages and some are displayed with a submenu as a list of all sub-pages. The pages in the menu are sorted according to the menu order specified for them. (Please see my code below).

Now, I would like to add some categories at a specific place in the menu and not sure how to better do it.

Read More

Is it possible to do it using wp_list_pages? What I like about my code is that whenever a subpage is added for a parent page that programmed to display all subpages, the newly added subpage will automatically appear in the site’s menu. As opposite to using Appearance->Menu functionality where a user will need to add a newly created subpage to the menu before it will appear on the site.

I might be easily over complicating it(!) and the only way to do it is via Appearance->Menu functionality. I would really appreciate any help and tips!

Here is the code that I use to display pages, some with all the sub-pages and some only at the top level.

//main nav: use wp_list_pages to display cirtain parent pages without any and with all child pages (a tree with parent)
$parents = array(5,7,17,61,19,25);
$children = array();
foreach($parents as $parent) {
  $child_pages = get_pages( "child_of=$parent" );
  if($child_pages){
    foreach($child_pages as $child_page){
      $children[] = $child_page->ID;
    }
  }
}
//add all the pages that need to be included without children
$parents = array_merge( (array)$parents, (array)array(31,23) );
//merge $parents and $children
$menu_pages = array_merge( (array)$parents, (array)$children );
$menu_pages_str = implode(",", $menu_pages); 
?> 

<ul class="menu wrap">
  <?php wp_list_pages( "sort_column=menu_order&title_li=&include=$menu_pages_str" ); ?>
</ul>

Related posts

Leave a Reply

1 comment

  1. wp_list_pages has limited functionality, and would be difficult to inject Categories into the mix without rewriting the function itself.

    Using the built in Menu functionality is likely the best way to go, because you can at least set individual item classes, allowing you to create Menu headers for your top level categories (having the header items use a “header” class or similar).

    You may also be able to just use the get_pages() function, which will return an array of the pages instead of just printing them onto the page. This will allow you add logic to the display of the data when iterating through the array.