Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come visualizzare un elenco di pagine figlio/bambino per una pagina genitore in WordPress

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Recentemente uno dei nostri lettori ci ha chiesto come visualizzare i figli/bambini di una pagina di WordPress?

Se il vostro sito web WordPress è organizzato con pagine figlio/bambino, potreste voler visualizzare le pagine figlio o le sottopagine sulla pagina principale del genitore. Potreste anche voler mostrare la pagina principale su ogni pagina secondaria per facilitare la navigazione.

In questo articolo vi mostreremo come visualizzare facilmente un elenco di pagine figlio/bambino per una pagina genitore in WordPress.

Displaying a list of child pages for a parent page in WordPress

Quando è necessario mostrare un elenco di figli/bambini?

WordPress dispone di due tipi di contenuto predefiniti, chiamati post / tipo di contenuto e pagine. Gli articoli sono contenuti del blog e di solito sono organizzati con categorie e tag.

Le pagine sono contenuti off o indipendenti che sono sempreverdi, come la pagina “Chi siamo” o la pagina “Contatti”.

In WordPress, le pagine possono essere gerarchiche, il che significa che è possibile organizzarle con genitori e figli/bambini.

Ad esempio, si può creare una pagina di prodotto con pagine figlio/bambino per le caratteristiche, i prezzi e l’assistenza.

Per creare una pagina figlia, seguite la nostra guida su come creare una pagina figlia in WordPress.

Dopo aver creato le pagine genitore e figlio/bambino, è possibile elencare le pagine figlio/bambino sulla pagina genitore principale.

Un modo semplice per farlo è modificare manualmente la pagina del genitore e aggiungere un elenco di colleghi individualmente.

Manually add child page links

Tuttavia, è necessario modificare manualmente la pagina genitore ogni volta che si aggiunge o si elimina una pagina figlio/bambino. Non sarebbe meglio se si potesse creare una pagina figlio/bambino e questa apparisse automaticamente come collega nella pagina genitore?

Detto questo, diamo un’occhiata ad altri modi dinamici per visualizzare rapidamente un elenco di pagine figlio/bambino sulla pagina genitore in WordPress. Vi mostreremo tre metodi, in modo che possiate scegliere quello più adatto a voi:

Metodo 1. Visualizzare le pagine dei figli/bambini sulla pagina del genitore utilizzando un plugin

Questo metodo è più semplice e consigliato a tutti gli utenti.

Per prima cosa, è necessario installare e attivare il plugin Page-list. Per maggiori dettagli, consultare la nostra guida passo passo su come installare un plugin di WordPress.

Dopo l’attivazione, è necessario modificare la pagina genitore e aggiungere semplicemente il seguente shortcode nel punto in cui si desidera visualizzare l’elenco delle pagine figlio/bambino.

[sottopagine]

Ora è possibile salvare la pagina e visualizzarla in anteprima in una nuova scheda del browser. Si noterà che visualizza un semplice elenco puntato di tutti i figli/bambini.

Plain list of child page links

Se si vuole, si possono aggiungere alcuni CSS personalizzati per modificare l’aspetto dell’elenco. Ecco alcuni esempi di CSS da utilizzare come punto di partenza.

ul.page-list.subpages-page-list {
    list-style: none;
    list-style-type: none;
    background-color: #eee;
    border: 1px solid #CCC;
    padding: 20px;
}

Dopo aver applicato il CSS personalizzato, è possibile visualizzare l’anteprima del genitore della pagina. Ecco come appariva sul nostro sito web WordPress di prova.

Child pages list with CSS

Il plugin fornisce una serie di parametri shortcode che consentono di impostare la profondità, le pagine escluse, il numero di elementi e altro ancora. Per maggiori dettagli, consultare la pagina del plugin per una documentazione dettagliata.

Metodo 2. Elencare i figli/bambini di una pagina genitore usando il codice

Questo metodo è un po’ avanzato e richiede l’aggiunta di codice al sito web WordPress. Se non l’avete mai fatto prima, date un’occhiata alla nostra guida su come copiare e incollare codice in WordPress.

Per elencare le pagine figlio/bambino sotto una pagina genitore, è necessario aggiungere il seguente codice in un plugin code snippets o nel file functions.php del tema:

function wpb_list_child_pages() { 
 
global $post; 
 
if ( is_page() && $post->post_parent )
 
    $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
else
    $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );
 
if ( $childpages ) {
 
    $string = '<ul class="wpb_page_list">' . $childpages . '</ul>';
}
 
return $string;
 
}
 
add_shortcode('wpb_childpages', 'wpb_list_child_pages');

Noi di WPBeginner consigliamo sempre di aggiungere codice in WordPress con WPCode. Permette di aggiungere facilmente codice personalizzato senza modificare i file del tema, così non dovrete preoccuparvi di rompere il vostro sito.

Per prima cosa, è necessario installare e attivare il plugin gratuito WPCode. Per istruzioni passo passo, consultare questa guida su come installare un plugin di WordPress.

Una volta attivato il plugin, navigare su Code Snippets ” Aggiungi snippet dalla dashboard di WordPress. Da qui, passare il mouse sull’opzione “Aggiungi codice personalizzato (nuovo snippet)” e fare clic sul pulsante “Usa snippet”.

Add a new custom code snippet in WPCode

Quindi, aggiungete un titolo per il vostro snippet e incollate il codice di cui sopra nella casella “Anteprima codice”.

Non dimenticate di scegliere “PHP Snippet” come tipo di codice dal menu a discesa sulla destra.

Paste code into WPCode plugin

A questo punto, è sufficiente spostare l’interruttore da ‘Inattivo’ ad ‘Attivo’ e fare clic sul pulsante ‘Salva snippet’ in alto nella pagina.

Activate and save your custom code snippet

Questo codice seleziona innanzitutto se una pagina ha un genitore o se la pagina stessa è un genitore.

Se è una pagina genitore, visualizza le pagine figlio/bambino ad essa associate. Se è una pagina figlio/bambino, visualizza tutte le altre pagine figlio della sua pagina genitore.

Infine, se si tratta solo di una pagina senza figli/bambini, il codice non farà nulla. Nell’ultima riga del codice, abbiamo aggiunto uno shortcode, in modo da poter visualizzare facilmente le pagine figlio/bambino senza modificare i template delle pagine.

Per visualizzare le pagine figlio/bambino è sufficiente aggiungere il seguente shortcode in una pagina o in un widget di testo nella barra laterale:

[wpb_childpages]

Non dimenticate di salvare le modifiche e di visualizzarle in anteprima in una scheda del browser. Ecco come appare sul nostro sito di prova.

Plain link list

È ora possibile creare uno stile per questo elenco di pagine utilizzando alcuni CSS personalizzati. Ecco alcuni esempi di codice CSS da utilizzare come punto di partenza.

ul.wpb_page_list {
    list-style: none;
    list-style-type: none;
    background-color: #eee;
    border: 1px solid #CCC;
    padding: 20px;
}

Metodo 3. Visualizzare dinamicamente le pagine dei figli/bambini senza shortcode

L’uso degli shortcode è comodo, ma il problema è che bisogna aggiungere gli shortcode in tutte le pagine che hanno figli/bambini.

Si può finire per avere shortcode in molte pagine e a volte ci si dimentica di aggiungerli.

Un approccio migliore sarebbe quello di modificare il file template della pagina nel tema, in modo da visualizzare automaticamente le pagine figlio/bambino.

Per farlo, è necessario modificare il template page.php principale o creare un template personalizzato nel tema.

È possibile modificare il tema principale, ma le modifiche scompariranno se si cambia o si aggiorna il tema. Per questo motivo sarebbe meglio creare un tema child e poi apportare le modifiche nel tema child.

Nel file del template della pagina, è necessario aggiungere questa riga di codice dove si desidera visualizzare le pagine figlio/bambino.

<?php wpb_list_child_pages(); ?>

Tutto-in-uno. Il tema child ora rileverà automaticamente le pagine figlio/bambino e le visualizzerà in un semplice elenco.

È possibile personalizzare gli stili con CSS e formattazione. Ecco un esempio di come il sito web di OptinMonster mostra la pagina genitrice e le sottopagine:

OptinMonster Sub Pages Example

Speriamo che questo articolo vi abbia aiutato a elencare i figli/bambini di una pagina genitore in WordPress. Potreste anche consultare la nostra guida sulle pagine più importanti da creare in un nuovo sito web WordPress e il nostro confronto tra i migliori builder di WordPress con trascina e rilascia per creare layout personalizzati senza alcun codice.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

81 commentiLascia una risposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

    • WPBeginner Support says

      The simplest method for what it sounds like you’re wanting would be to not have content on the parent page and only have your content in the child pages.

      Admin

  2. Emmanuel Husseni says

    Hello Wpbeginner,

    Please how can i sort all the child page alphabetically on the parent page. I’ve follow all step but the sub pages are showing randomly on the parent page.

    Waiting for response. ….Thanks

  3. Aaro says

    Can I assign a css class to this function? So that when I make css changes to ul elements it wouldn’t affect other ul’s on the site.
    Or any other simple solution for this?

  4. Keshav Murthy says

    Hi, WPB Team,

    Thank you so much for this Snippet and the tutorial.

    It saved my ton of time and helped me too.

    With Warm Regards,
    Keshav Murthy

  5. Gary Granai says

    I installed the plugin code snippets in wordpress 4.9.8

    I copied the code on https://www.wpbeginner.com/wp-tutorials/how-to-display-a-list-of-child-pages-for-a-parent-page-in-wordpress/#respond and added it to a new snippet in code snippets.

    I made a page and then a page which was given the attribute of having the first page as the parent page.

    The child parent relationship is shown in the list of pages in the attributes drop down.

    When I open the parent page I see nothing that shows a child page.

    I then tried using the functions.php page.

    I added the code copied from https://www.wpbeginner.com/wp-tutorials/how-to-display-a-list-of-child-pages-for-a-parent-page-in-wordpress/#respond to the bottom of the code on the functions page.

    When I open the parent page, I it does not display. What displays is an error message saying there is unexpected code.

    I restored the functions.php page to its original statuc.

    What changes must I make to what I have tried to do.

    • WPBeginner Support says

      Hi Gary,

      Make sure that you publish the child page before testing the code. Also carefully copy the code again to make sure that you are not copying the numbers or any unexpected characters.

      Admin

  6. Itika says

    I have a question. I have added sub pages in parent page but when I am opening the site in mobile and clicking on parent page it opens the empty parent page. To view the drop down sub pages one have to hold the button of parent page. How can I fix it. I don’t want that empty page to open. I want that if we touch on parent page it opens the drop down menu.
    Please suggest how to do it.

  7. Denise says

    For third level pages (grandchild), I want to show the same menu that is seen on the child pages (all the child links of the parent). With this snippet, when on a grandchild page, I only see the other grandchild pages in the menu. How would this code need to be modified to show the all child links even when on grandchild pages?

  8. Meredith L says

    I’m relatively new to blogging and I recently switched over to the Kale WordPress theme. I have been trying to do page attribute pages (under the parent page Recipes) so I can have separate categories for appetizers, desserts, etc. Everything seems to go through on the admin part but then on the site itself there are no page attributes/drop down form the Recipes category. What am I doing wrong? It is all set to public so I’m not sure what the problem is.

  9. Daves says

    Thank you for this code. But I don’t want this to be shown on the homepage (static page), just on the parent pages only. Please how can it be done?

    Thank you.

  10. Boris Budeck says

    I am using Generatepress Theme (created a child theme from it for customizing) and I can’t get this to work. The shortcode is displayed in the output page, it seems it is not even ercognized as being a shortcode. I use Elementor widgets and neither text nor shortcode widgets work.

    Any idea of how to make it work when using elementor widgets?

  11. Frederic says

    a great post, it’s exactly what I’m looking for since many hours ! and it works like a charm, just adding the code in the function.php of the theme then adding the short code in the page where I want the sub pages to appear, and voilà!!!
    wonderful, thanks a lot for your generosity !!

  12. Ron says

    Like with so many of the snippets we find, one has to go through all the comments in order to get it to work. What’s wrong with testing what you write?

  13. Alicia says

    Can you do a drop down menu for parent/child pages on wordpress.com, or does it have to be the .org version?

  14. Rudy says

    Using this code ends up displaying the parent page along with the child pages, which is redundant. As I understand it, what we really need is to display only the child pages, not the parent page. Any suggested modification that can do this?

  15. Milos says

    On plugins update, for some strange reason I always get an error:

    Fatal error: Cannot redeclare wpb_list_child_pages() (previously declared in …/wp-content/themes/pagelines/functions.php:25) in …/wp-content/themes/pagelines/functions.php on line 34

  16. ethann says

    Hello great article,
    Can you please help me creating a dropdown of child pages in parent page.I need this functionality for one of my wordpress project and i am totally newbie to wordpress.

  17. Alex says

    Am I the only one that cannot get it to work?

    I have the following structure

    About
    — Page 1
    — Page 2
    — Page 3

    When on the “About” or a child page (1, 2 or 3) I would like to have a list with my parent page (About) and all children (1, 2, 3) – Anyone got that working?

    Thanks! :)

    • Kendra says

      OMG sorry this is annoying Please ignore my other posts. Didn’t realize you couldn’t paste code into the comments.

      I was NOT able to get it to work with wpb_list_child_pages();

      I WAS able to get it to work with echo do_shortcode( ‘[wpb_childpages]’)

      And to get the title of the parent page, i inserted this above the child page list:
      $current = $post->ID;

      $parent = $post->post_parent;

      $grandparent_get = get_post($parent);

      $grandparent = $grandparent_get->post_parent;

      PHP if ($root_parent = get_the_title($grandparent) !== $root_parent = get_the_title($current)) {echo get_the_title($grandparent); }else {echo get_the_title($parent);

  18. Jean Bishop says

    I am using this code and it works great. Is it possible to also display categories in menus along with pages?

  19. Michelle says

    Hi,

    I want to do the following

    Parent page must be either for sale and or for rent
    Then I want the child for example a province (gauteng) to link to the for sale and the for rent parent.
    How do I do that?

    Michelle

  20. Zakhar says

    How can i create shortcode with param, for example, [wpb_childpages id=”1″], where id=”1″ is an id of parent page?

  21. Aander says

    Thank you,

    Could you explain, please, how can I organize child pages in drop down list that would be accessible through the parent page? (I don’t want the visitors could see all child pages in a form of a blogroll.)

    I.e., on the parent page I want to create drop down list (listbox) to which child pages would be added in predefined order (say in alphabetical order). After reading Introduction a visitor can proceed by choosing any page from the list at her wish (child pages has no logical connection so in any case she will search the exact page).

    Is ‘my dream’ realizable?

    Thank you again.

  22. Astrid says

    Hi WPBeginner Staff,

    I used the code you guys provided with the “short code option” and it worked (links to child pages). However, I wanted to use the permanent option, and that didn’t work.

    When I added this line of code [ ] the parent page returns a 500 error and no child pages are displayed at atll.

    What am I doing wrong?

    On a side note if I wanted to display and excerpt with its respective image how would I go about it? Thanks!

    • Astrid says

      I was able to figure this out.

      I added the code snippet then added this shortcode [wpb_childpages] to the parent page where I wanted the child pages displayed. Awesome!

      Now in order to display excerpts and an image would I use the same queries– just like posts under a category.

      Thanks in advance :)

      • Jade says

        Hey I was wondering what you meant by ‘query’? How exactly did you get the excerpts and images to display in the parent page?

        Thanks!

  23. Pradeep says

    Could someone confirm that the example page used in this tutorial http://optinmonster.com/how-it-works/ uses this feature or not? To me it looks like it they are using tabs, instead of child pages.

    If I’m right, could someone direct me to a resource to get that feature, as I’m desperately looking for a fluid solution like the one they have in that page?

    Many thanks,

    Pradeep

  24. Andrew Roberts says

    For the non-shortcode option, you might want to let users know they need to either change
    return $string; to
    echo $string; or
    in their page template echo out the function
    echo page_list_child_pages();

    Thanks to Erik for pointing this out above

  25. Howard says

    Hi, I can get this to work when I am visiting my domain with a subdirectory (e.g – example.com/home) but when viewing the site without this (example.com) the list of sub pages is not listed. Can anyone point me as to where I am going wrong?

    Thanks in advance – very new to WordPress.

  26. Emily Jennewein says

    How do you get this function to display the parent page itself at the top of the list along with the list of child and grandchild pages? On the child pages it does not list the parent page.

  27. Jenny says

    Is there now a plugin that can do same ?

    and also can we decide where the box with submenus pages will go in any are of the page not just top of page? Using a plugin

  28. WPBeginner Staff says

    Yes it can be used for custom post types. Like this:


    function wpb_list_child_pages() {

    global $post;

    if ( 'movie' == get_post_type() && $post->post_parent )

    $childpages = wp_list_pages( 'post_type=movie&sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
    else
    $childpages = wp_list_pages( 'post_type=movie&sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );

    if ( $childpages ) {

    $string = '' . $childpages . '';
    }

    return $string;

    }

    add_shortcode('wpb_childpages', 'wpb_list_child_pages');

  29. dpc says

    Is there a way to modify this in order to print custom post type child posts on a custom post type post page? Thanks, it is very handy!

  30. Sokeara says

    It’s very greate for me! Anyways I would like to know how can I display title and thumbnail of child page to parent page.

    • Ashley Bell says

      Hi, I have the same query. I really like how the list is styled on the Beginners Blueprint page but I have no idea how to start. Can someone recommend an article to read or give some advice, thanks.

  31. amitabha197 says

    There is an error in the pages which are not having child pages so I have slightly modified
    if( count($childpages) != 0 ) {
    $string = ” . $childpages . ”;
    }

    instead of
    if( $childpages ){
    $string = ” . $childpages . ”;
    }

  32. Coen Siebenheller says

    I’ve added the code to the functions.php and when i add the [wpb_childpages] shortcode in side my text it works. But when try to add to one of my templates it doesn’t show a thing. Anybody knows what i’m doing wrong?

  33. Quin says

    This is brilliant, thanks.

    Is there a way to adapt it so the Parent displays the Grandchild, and not the Child?

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.