Skip to content

Instantly share code, notes, and snippets.

@soutar
Last active August 29, 2015 14:00
Show Gist options
  • Save soutar/11370212 to your computer and use it in GitHub Desktop.
Save soutar/11370212 to your computer and use it in GitHub Desktop.
Quick infinite-depth subnav for WordPress
<?php
function cad_section_nav($title = true) {
global $post;
if (!is_object($post)) return;
$section = get_post_ancestor($post->ID);
$pages = get_pages(array(
'parent' => $section->ID
)
);
$sectionPermalink = get_permalink($section);
if ($title) echo "<a href=\"{$sectionPermalink}\">{$section->post_title}</a>";
echo pages_as_list($pages, $post);
}
function pages_as_list($pages, $currentPage) {
if (!count($pages)) return false;
$output = "<ul>";
foreach ($pages as $item) {
$permalink = get_permalink($item->ID);
$children = get_pages(array('parent' => $item->ID));
$active = post_is_ancestor_of($currentPage, $item) || $item->ID == $currentPage->ID;
$class = ($active ? 'active' : '');
if (count($children) && $active) {
$output .= "<li class=\"{$class}\">";
$output .= "<a href=\"{$permalink}\">{$item->post_title}</a>";
$output .= pages_as_list($children, $currentPage);
$output .= "</li>";
} else {
$output .= "<li class=\"{$class}\"><a href=\"{$permalink}\">{$item->post_title}</a></li>";
}
}
$output .= "</ul>";
return $output;
}
function get_post_ancestor($postID) {
$post = get_post($postID);
if (!is_object($post)) return;
while ($post->post_parent != 0): $post = get_post($post->post_parent); endwhile;
return $post;
}
function post_is_ancestor_of($post, $ancestor) {
if (!is_object($post) || !is_object($ancestor)) return;
$ancestors = get_post_ancestors($post);
return (in_array($ancestor->ID, $ancestors));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment