Subpagina’s samen met hoofdpagina’s tonen in sidebar

Al hoe fijn WordPress werkt, het is soms best nog wel eens lastig om alles uit de kast te halen als het om het tonen van subpagina’s i.c.m. met hoofdpagina’s in bijvoorbeeld een sidebar. Ofwel.. Child Pages samen met Parent Pages tonen.

WP Engineer publiceerde vandaag een fijne hack om dit op te lossen.

Important for us are 2 things: the top page is always at the end of the array and it can return an empty array. So we just go to the end of the array and for the case that there is no parent page, we display all the subpages of this page. We write a function in our functions.php because it is easier to maintain, and may also be used in several sidebars.

De oplossing die kiezen is het toevoegen van een functie aan je functions.php.

function wpe_highest_ancestor(){
    global $post;
    $page_ancestors = end($post->ancestors);
    if(!empty($page_ancestors)){
        $child_of = $page_ancestors;
    }else{
        $child_of = $post->ID;
    }
    return $child_of;
}

Hiermee maak je het mogelijk om bijvoorbeeld de volgende code aan je sidebar.php toe te voegen:

<ul class="sidebar">
  <?php
  $child_of = wpe_highest_ancestor();
  wp_list_pages('child_of='.$child_of.'&title_li=<h5>'.esc_attr(get_the_title($child_of)).'</h5>');
  ?>
</ul>

Naast deze twee juweeltjes loont het ook om nog even naar de betreffende Codex pagina te gaan, ook daar staan interessante oplossingen.

Gravity Forms Plugin for WordPress

Laat wat van je horen

*