Skip to content

Instantly share code, notes, and snippets.

@bobbydank
Last active August 1, 2022 15:45
Show Gist options
  • Save bobbydank/06f9aaa57962c9453b8c5bb705e974c5 to your computer and use it in GitHub Desktop.
Save bobbydank/06f9aaa57962c9453b8c5bb705e974c5 to your computer and use it in GitHub Desktop.
Simple function for creating a subnav in your Wordpress theme
<?php
/**
* author: Robert Danklefsen
* website: https://www.catchylabs.com/
*
* Simple function for creating a subnav in your Wordpress theme
*/
function catchylabs_get_top_parent_page_id() {
global $post;
$ancestors = $post->ancestors;
// Check if page is a child page (any level)
if ($ancestors) {
// Grab the ID of top-level page from the tree
return end($ancestors);
} else {
// Page is the top level, so use it's own id
return $post->ID;
}
}
$ancestor_id = catchylabs_get_top_parent_page_id();
$children = get_pages(array('child_of' => $post->post_parent, 'parent' => $post->post_parent, 'sort_order' => 'asc', 'sort_column' => 'menu_order'));
if ($children) :
?>
<div class="subnav right">
<ul>
<?php foreach ($children as $child) : ?>
<li class="<?= ($child->ID == $post->post_parent) ? "current_page_item" : ""; ?> <?= ($child->ID == $post->ID) ? "current_page_item" : ""; ?>">
<a href="<?= get_the_permalink($child->ID) ?>"><?= $child->post_title ?></a>
</li>
<?php endforeach; ?>
</ul>
<div class="mobile-select">
<select onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value="-1">- More Products -</option>
<?php foreach ($children as $child) : ?>
<option value="<?= get_the_permalink($child->ID) ?>"><?= $child->post_title ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment