Drupal’s “Menu Block” in WordPress

As a company that does both Drupal and WordPress websites, it can be frustrating sometimes when functions┬áthat are so easy for one platform are so difficult to duplicate on the other. One example is the Menu Block functionality that will create a submenu relative to whatever page you’re on. Like many things in WordPress, it often boils down to pasting a snippet of code in your template file.

The key is the feature is leveraging WordPress’s wp_list_pages function and grabbing the current page’s parent ID.

Paste this snippet into your theme’s sidebar template file (or anywhere else you want it to show up).

<div id="subnav">
 $ancestor_id = $post->post_parent;
 $ancestors = get_ancestors($post->ID, 'page');
 if(isset($ancestors[1])) {
 $ancestor_id = $ancestors[1];
 $descendants = get_pages(array('child_of' => $ancestor_id));
 $incl = "";

 foreach ($descendants as $page) {
 if (($page->post_parent == $ancestor_id) ||
 ($page->post_parent == $post->post_parent) ||
 ($page->post_parent == $post->ID))
 $incl .= $page->ID . ",";

 <?php wp_list_pages(array("child_of" => $ancestor_id, "include" => $incl, "link_before" => "", "title_li" => "", "sort_column" => "menu_order"));?>

This code will sort the pages by on the page order, so make sure you assign unique values for each or you’ll get unexpected sorting results.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.