0

What I'm currently trying to achieve is displaying certain menus on certain pages using one template and conditional statements, like so:

if (is_page('donate')){
wp_nav_menu(array(
            'menu'  =>  'donate',
            'container' => false,
            'menu_class'      => 'side-menu'
        ));
} elseif (is_page('about-us')) {
wp_nav_menu(array(
            'menu'  =>  'about',
            'container' => false,
            'menu_class'      => 'side-menu'
        ));
}

As all these pages use the same template I needed something that allowed the relevant submenus to display on the relevant pages, which works fine. The problem I'm now having though, is that both pages donate and about (and more to follow) have subpages, is it at all possible to display the relevant menu on ALL the subpages as well? Thus if you're on the donate page, or a child of the donate page the donate menu will be displayed, etc.

1

Use get_ancestors to get the page parent, then check against that value instead of checking against the name.

$ancestors = array();
$ancestors = get_ancestors($post->ID,'page');
$parent = (!empty($ancestors)) ? array_pop($ancestors) : $post->ID;
if (!empty($parent)) {
  switch ($parent){
    case 1 :
      // menu for parent page ID 1
    break;
    case 2 :
      // menu for parent page ID 2
    break;
  } 
}

And so on. Your numbers will need to match against the IDs of the parent pages.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.