WordPress.org

Ready to get started?Download WordPress

Forums

Child page within unordered list (4 posts)

  1. tonicbox
    Member
    Posted 5 years ago #

    Hi All

    I've got some code that works to some extent, but I can't quite get it right.

    Basically, I've got an unordered list containing top level pages. If you are on a page that has children (sub pages), they should appear below in the unordered list. For example.

    Here is my top-level menu:

    Home
    Services
    Portfolio
    About
    Contact

    The page 'Services' has a sub page, so when you are on the 'Services' page the menu should look like this:

    Home
    Services
    Sub page of services
    Portfolio
    About
    Contact

    My code does this:

    Home
    Services
    Portfolio
    About
    Contact
    Sub page of services

    So although I'm managing to get the sub page acknowledged by WP, it won't show it under the parent page in the menu.

    Here's the code:

    <ul><?php wp_list_pages('depth=1&title_li='); ?>
    <!-- This checks to see if the page being viewed is a parent of sub pages -->
    <?php
    	global $wp_query;
    
    	if( empty($wp_query->post->post_parent) ) {
    	$parent = $wp_query->post->ID;
    	} else {
    	$parent = $wp_query->post->post_parent;
    	} ?>
    	<!-- This line runs if it is a parent -->
    	<?php if(wp_list_pages("title_li=&child_of=$parent&echo=0" )): ?>
    	<ul>
    		<?php wp_list_pages("title_li=&child_of=$parent" ); ?>
    	</ul>
    	<?php endif; ?>
    
    </ul>

    Although the HTML markup for the list seems correct, WP just sticks the sub page at the end of the unordered list a separate unordered list.

    Help!

  2. Sayontan Sinha
    Member
    Posted 5 years ago #

    The call to wp_list_pages generates the html markup for the pages, including the <ul> and the </ul> tags. So your first call is actually printing out the entire first level and closing the list, then your second call is creating the second level.

    You might want to set depth=2 on wp_list_pages, or you might instead consider using get_pages for your first call, then iterate through the list and run get_pages for each top level.

  3. tonicbox
    Member
    Posted 5 years ago #

    Hi Sayontan

    Thanks for the reply. Could you give me some more detail on your second option, using get_pages etc?

  4. tonicbox
    Member
    Posted 5 years ago #

    I've just tried using depth=2, and although the sub page appears where it should, it appears on all pages, which is what I thought would happen.

    I only want the sub pages to appear when you are on a page that has sub pages.

Topic Closed

This topic has been closed to new replies.

About this Topic