WordPress - Displaying Custom-Formatted Links To Page Children

Submitted by Kenny on Sat, 04/03/2010 - 22:40

This is just a quick and easy tip, but it was harder to find the answer to than I would have expected. (...or maybe I just didn't appease the Google Gods correctly when searching.)

If you have a page hierarchy within your WordPress site and you want to display (such as in the sidebar) the immediate children of the current page that you're on, here's the code to do it.

    // will display the subpages of this top level page
    $children = wp_list_pages("title_li=&child_of=" . $post->ID . "&echo=0");
    if ($children)
        // custom formatting goes here, just print
        // $children when you want to render the link
        echo '<div id="pagelist">' . "\n";
        echo "<ul>\n$children\n</ul>\n";
        echo '</div> <!-- end div id="pagelist" -->' . "\n";
    } // end if test

Please note that this method only lets you custom format the display around the actual link. wp_list_pages() will return the text with the anchor link already wrapped around it. I haven't dug into how to further format the link.

I hope that helps!