Search code examples
phpwordpressmenutitle

Wordpress: Show the parent menu title


I want to show the parent menu item above the submenu but when there is no submenu the parent menu item must not be showing then.

Now i use this code (page.php):

<div class="left">      
    <h2>
        <?php
            $parent_title = get_the_title($post->post_parent);
            echo $parent_title;
        ?>
    </h2>

    <?php wp_nav_menu( array('container_class' => 'Hoofdmenu','theme_location' => 'Hoofdmenu','sub_menu' => true) ); ?>

    <?php get_sidebar(); ?>
</div>

Output:

TITLE PARENT MENU
Subitem
Subitem
Subitem
------------
Widgets and stuff not important.

But with this code the parent menu item (title) is always visible even when there is no submenu...


Solution

  • Looks like what you need is a combination of checking if the page is a parent or not and then also seeing if it has children.

    Something like this should work.

    <?php
    
    if ( is_page($post->ID) && $post->post_parent ) {
      $children = get_pages('child_of='.$post->post_parent);
    } else {
      $children = get_pages('child_of='.$post->ID);
    }
    
    ?>
    
    <?php if($children):?>
      <h2>
        <?php 
        $parent_title = get_the_title($post->post_parent);
        echo $parent_title;
        ?>
      </h2>
    <?php endif;?>