Wordpress Dynamic Page Menu Navigation

19th May 2010

After writing the function that creates a list of pages that are children of a given page in Wordpress I needed something more robust and automatic. To that end I created a plugin that will create a widget that contains a dynamically created menu of pages.

The widget figures out what page is currently being displayed and will climb the page tree until it finds the root page. Whilst climbing the page tree the plugin will keep the path to the currently selected page and when the tree is printed out the path will be open. It is best suited for sites that have a solid hieratic page structure, rather than a simple blogging site.

In terms of efficiency I have tested it with pages nested up to 25 levels deep with only a small decrease in page load. However, for the average small Wordpress site this plugin is perfect as pages will only be nested a few levels deep.

  1. post_type == 'page') {
  2. if ($post->post_parent > 0) {
  3. $root = findPathInformation($post);
  4. $pages = traversePageTree($root['root'], $root['activepath'], $root['depth']);
  5. } else {
  6. $root = $post;
  7. $pages = traversePageTree($root, array($root->ID), 1);
  8. }
  9. echo printPageTree($pages);
  10. }
  11. }
  12.  
  13. /**
  14.  * From a single page find out how deep it is
  15.  *
  16.  * @param object $page The current page.
  17.  *
  18.  * @return array An array of information about the page and the path.
  19.  */
  20. function findPathInformation($page)
  21. {
  22. // Go up the tree and see what is in the path.
  23. $reverse_tree = climbPageTree($page);
  24. // Flattern the tree to get the current active path.
  25. $activePath = flattenTree($reverse_tree);
  26.  
  27. // Make sure current page is in the active path.
  28. $activePath[] = $page->ID;
  29.  
  30. $root = $reverse_tree[0];
  31.  
  32. // Set to 2 as if we are in this code we are in the level just below root.
  33. $depth = 2;
  34.  
  35. // Recursivley loop through the pages and find the root page and the depth.
  36. while (is_array($root->post_parent)) {
  37. ++$depth;
  38. $root = $root->post_parent[0];
  39. }
  40.  
  41. return array('root' => $root, 'depth' => $depth, 'activepath' => $activePath);
  42. }
  43.  
  44. /**
  45.  * Flatten the tree into a single array.
  46.  *
  47.  * @param array $tree A multi dimensional array of pages.
  48.  *
  49.  * @return array A single dimensional array of pages.
  50.  */
  51. function flattenTree($tree)
  52. {
  53. $flat = array();
  54.  
  55. while (is_array($tree[0]->post_parent)) {
  56. $flat[] = $tree[0]->ID;
  57. $tree = $tree[0]->post_parent;
  58. }
  59.  
  60. $flat[] = $tree[0]->ID;
  61.  
  62. return $flat;
  63. }
  64.  
  65. /**
  66.  * Find out if the current page is in the active path.
  67.  *
  68.  * @param integer $id The ID of the current page.
  69.  * @param array $activePath An array of ID's of the pages in the current path.
  70.  *
  71.  * @return boolean True if the page is in current path, otherwise false.
  72.  */
  73. function inActivePath($id, $activePath)
  74. {
  75. if (in_array($id, $activePath)) {
  76. return true;
  77. } else {
  78. return false;
  79. }
  80. }
  81.  
  82. /**
  83.  * Starting with the current page go up level after level until the root page
  84.  * reached. This function will run one SQL query for every level.
  85.  *
  86.  * @global wpdb $wpdb The current Wordpress database connection object.
  87.  *
  88.  * @param object $page The current page.
  89.  *
  90.  * @return
  91.  */
  92. function climbPageTree($page)
  93. {
  94. global $wpdb;
  95. $parent = $wpdb->get_results("SELECT ID, post_title, post_parent FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'page' AND ID = " . $page->post_parent . " ORDER BY menu_order, post_title", OBJECT);
  96.  
  97. if (count($parent) > 0) {
  98. foreach ($parent as $item => $par) {
  99. if ($par->post_parent != 0) {
  100. $parent_parent = climbPageTree($par);
  101. if ($parent_parent !== false) {
  102. $parent[$item]->post_parent = $parent_parent;
  103. }
  104. } else {
  105. // Reached top of tree
  106. return $parent;
  107. }
  108. }
  109. }
  110.  
  111. return $parent;
  112. }
  113.  
  114. /**
  115.  * Traverse the page structure and create a tree of the pages.
  116.  *
  117.  * @global wpdb $wpdb The current Wordpress database connection object.
  118.  *
  119.  * @param object $page The page to start the tree traversal from, usually root.
  120.  * @param array $activePath An array of page ID's in the active path.
  121.  * @param integer $maxdepth The maximum depth to follow the traversal
  122.  * @param integer $depth The current depth of the traversal.
  123.  *
  124.  * @return array A tree of pages.
  125.  */
  126. function traversePageTree($page, $activePath = array(), $maxdepth = 10, $depth = 0)
  127. {
  128. if ($depth >= $maxdepth) {
  129. // We have reached the maximum depth, stop traversal.
  130. return array();
  131. }
  132.  
  133. // Get Wordpress db object.
  134. global $wpdb;
  135.  
  136. $children = $wpdb->get_results("SELECT ID, post_title, post_parent FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'page' AND post_parent = " . $page->ID . " ORDER BY menu_order, post_title", OBJECT);
  137. if (count($children) > 0) {
  138. foreach ($children as $item => $child) {
  139. if (inActivePath($child->ID, $activePath)) {
  140. // Current page is in active path, find the children.
  141. $children[$item]->children = traversePageTree($child, $activePath, $maxdepth, $depth + 1);
  142. }
  143. }
  144. }
  145.  
  146. return $children;
  147. }
  148.  
  149. /**
  150.  * Print out the page tree as created by the traversePageTree() function.
  151.  *
  152.  * @see traversePageTree()
  153.  *
  154.  * @param array $pages A tree of pages.
  155.  */
  156. function printPageTree($pages)
  157. {
  158. $class = '';
  159. $output = '';
  160. $output .= "\n\n";
  161. foreach ($pages as $page) {
  162. if (is_page($page->ID) === true) {
  163. $class = ' class="on"';
  164. }
  165. $output .= "ID) . "\" title=\"" . $page->post_title . "\">" . $page->post_title . "";
  166. $class = '';
  167. if (isset($page->children) && count($page->children) > 0) {
  168. $output .= printPageTree($page->children);
  169. }
  170. $output .= "\n";
  171. }
  172. $output .= "\n";
  173. return $output;
  174. }
  175.  
  176. /**
  177.  * Widget function
  178.  *
  179.  * @param array $args
  180.  */
  181. function pageMenuNavigationWidget($args)
  182. {
  183. extract($args);
  184.  
  185. echo '';
  186. echo printPages();
  187. echo '';
  188. }
  189.  
  190. register_sidebar_widget(__('Page Menu Navigation'), 'pageMenuNavigationWidget');
  191. $wp_registered_widgets[sanitize_title('Page Menu Navigation')]['description'] = 'Creates a navigation menu.';

If you like this plugin and find it useful then let me know and I will add it to the Wordpress plugin centre. I'm sure there are some improvements that could be made to the plugin, if you think of any then leave a comment and let me know.

Update 01/11/2010

I have had another look at generating a dynamic menu using the Walker_Page class. The good thing about using the Walker_Page method is that it can be used to override the default page widget that comes with WordPress.

Comments

Permalink
I have been scouring the Internet to find something that would work like this. I've gotten close in some code but just couldn't get it to work. UGGG Great great work!!!! I can't believe I'm the first to find this. Thank you thank you thank you!!!!!!!! And thank God for you!

Acts7 (Sat, 06/05/2010 - 09:27)

Permalink
Nice work but i can't help thinking this would be easier:  if($post-post_parent) $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); else $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0"); if ($children) { ?>
     echo $children; ?
Or am i missing something?

Dirtyone30 (Wed, 10/20/2010 - 12:30)

Permalink
Maybe it's good to have a look at navigo, a rather old plugin, that still works on current WP-Versions as it seems to be rather simple (but powerfull), even though no widget (but would work in a text-widget via

lobster (Wed, 01/05/2011 - 11:41)

Permalink
The article is really awesome, and I got lots of valuable information from the article, it’s really very helpful for the visitors.

Billy Bowden (Sat, 01/22/2011 - 18:21)

Add new comment

The content of this field is kept private and will not be shown publicly.