WordPress – displaying child pages on parent page as sidebar menu items.

0
31

Here I am sharing a WordPress code snippet to display child pages on parent page as menu items without using any plugin. You ma probably use this code to display sidebar menu with child menu items of current parent page.

wordpress child pages in sidebar

STYLING SIDEBAR MENU

In above screen cap you noticed that each level of sidebar menu item is generating with a different formatting style and indentation, so in this code i have added a specific class for that. If you like you can replace it with class name of your own.

As per below code you can prepare classes like this –

1. .LNB .title {} = styling title or current parent page
2. .links li.current_page_item a {} = styling current page
3. .links .current_page_item .children a {} = styling child pages of current selected parent

CODE TO GENERATE SIDEBAR MENU WITH CHILD PAGES

You can place below code in sidebar.php of your them folder, or in any other theme file where you want to display child pages of current parent page

<?php if ( is_page() ) { ?>
  if($post->post_parent)
    $children = wp_list_pages('title_li=&child_of='.$post->post_parent.'&echo=0'); else
    $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
    if ($children) { ?>
     <section class="LNB">
     <div class="title"><?php
     $parent_title = get_the_title($post->post_parent);
     echo $parent_title;
     ?><span></span></div>
     <ul class="links">
     <?php echo $children; ?>
     </ul>
     </section>
  <?php } } ?>

The code above first check if this is a page and not a post. Then it check if this is a parent page having child pages, and display parent page title in a div with class name “title” then it display child of current page to the nth level. If current page has no child page, code will not display anything.

I hope this post really helps you in preparing sidebar menu items. Don’t forget to give +1 and leave your precious comments.

LEAVE A REPLY

Please enter your comment!
Please enter your name here