En av våra läsare frågade oss nyligen hur man visar child-sidor på en WordPress page?
Om du organiserar din website i WordPress med parent- och child pages, kanske du vill displayed your child pages eller sub pages på huvudsidan parent. Du kanske också vill visa huvudsidan på varje underliggande page för enkel browsing.
I den här artikeln visar vi hur du enkelt kan visa en lista med child pages för en parent page i WordPress.
När du behöver visa en lista över Child Pages?
WordPress levereras med två standard post typer som anropas posts och pages. Posts är blogginlägg, och de är vanligtvis organiserade med kategorier och tags.
Pages är enstaka eller fristående content som är vintergröna, som till exempel en ”About us”-sida eller en ”Contact us”-sida.
I WordPress kan pages vara hierarkiska, vilket innebär att du kan organisera dem med parent- och child-sidor.
You kanske till exempel vill skapa en produktsida med child pages för funktioner, priser och support.
För att skapa en child page följer du vår guide om hur du skapar en child page i WordPress.
När du har skapat dina parent- och child pages kanske du vill lista child pages på huvudsidan parent.
Nu är ett enkelt sätt att göra detta genom att manuellt redigera parent page och add to en lista med länkar individuellt.
Du måste dock redigera parent-sidan manuellt varje gång du addar eller tar bort en child page. Skulle det inte vara trevligare om du bara kunde skapa en child page och den automatiskt skulle visas som en link på parent page?
Med detta sagt, låt oss ta en titt på några andra dynamiska sätt att snabbt displayed en lista över child pages på parent page i WordPress. Vi visar dig tre metoder, så att du kan välja den som är bäst för dig:
Metod 1. Display Child Pages på Parent Page med hjälp av ett plugin
Denna metod är enklare och rekommenderas för alla användare.
Först måste du installera och aktivera pluginet Page-list. För mer detaljer, se vår steg-för-steg guide om hur du installerar ett WordPress plugin.
Vid aktivering måste du redigera parent page och helt enkelt add to följande shortcode där du vill visa listan över child pages.
[undersidor]
Du kan nu save your page och previewa den i en new tabs i webbläsaren. You’ll notice that it displays a simple bulleted list of all the child pages.
Om du vill kan du add to lite custom CSS för att ändra listans appearance. Här är några exempel på CSS som du kan använda som utgångspunkt.
ul.page-list.subpages-page-list {
list-style: none;
list-style-type: none;
background-color: #eee;
border: 1px solid #CCC;
padding: 20px;
}
När du har tillämpat din custom CSS kan du previewa den parent page. Så här såg det ut på vår test website WordPress.
Pluginet ger ett gäng shortcode-parametrar som tillåter dig att ställa in djup, utesluta pages, antal objekt och mer. För detaljer, vänligen se pluginets page för detaljerad documentation.
Metod 2. Lista Child Pages för en Parent Page med hjälp av kod
Den här metoden är lite mer avancerad och är obligatorisk för att du ska kunna add to kod till din website i WordPress. Om du ej har gjort detta tidigare, vänligen ta en titt på vår guide om hur man copy and paste kod i WordPress.
För att lista barnsidor under en huvudsida måste du lägga till följande kod i ett code snippets plugin eller i ditt temas functions.php-fil:
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');
På WPBeginner rekommenderar vi alltid att lägga till kod i WordPress med WPCode plugin.
WPCode allow you to easily add custom code without editing your theme files, so you don’t have to worry about breaking your site.
Först måste du installera och aktivera det gratis WPCode plugin. För steg-för-steg-instruktioner, se den här guiden om hur du installerar ett plugin för WordPress.
När pluginet är aktiverat navigerar du till Code Snippets ” Add Snippet från din WordPress dashboard. Därifrån hoverar du musen över alternativet ”Add Your Custom Code (New Snippet)” och klickar på knappen ”Use snippet”.
Lägg sedan till en rubrik för ditt snippet och klistra in koden ovan i boxen ”Code Preview”.
Glöm inte att välja ”PHP Snippet” som code type i dropdown-menyn till höger.
Efter det är det bara att toggle omkopplaren från ”Inaktiverad” till ”Aktiv” och klicka på knappen ”Save Snippet” högst upp på sidan.
Den här koden kontrollerar först om en page har en parent eller om själva page är en parent.
Om det är en parent page visas de child pages som är kopplade till den. Om det är en child page, visas alla andra pages som är underordnade till parent page.
Slutligen, om detta bara är en page utan någon child eller parent page, så kommer koden helt enkelt inte att göra någonting. På den sista raden i koden har vi add to en shortcode, så att you enkelt kan displayed child pages utan att ändra dina page templates.
För att displayed child pages add to följande shortcode i en page eller textwidget i sidebaren:
[wpb_childpages]
Glöm inte att save dina ändringar och previewa dem i en ny tabs i webbläsaren. Så här ser det ut på vår testsite.
Du kan nu styla den här page-listan med hjälp av lite customize CSS. Här är några exempel på CSS-kod som du kan använda som utgångspunkt.
ul.wpb_page_list {
list-style: none;
list-style-type: none;
background-color: #eee;
border: 1px solid #CCC;
padding: 20px;
}
Metod 3. Dynamiskt visa sidor för barn utan någon shortcode
Att använda shortcodes är bekvämt, men problemet med dem är att du måste add shortcodes på alla pages som har parent eller child pages.
Det kan sluta med att du har shortcodes på många pages, och ibland kanske du till och med glömmer att add to dem.
Ett bättre tillvägagångssätt skulle vara att edit filen page template i ditt theme, så att den automatiskt kan visa child pages.
För att göra det måste du edit main page.php
template, eller skapa en custom page template i your theme.
Du kan editera ditt huvudtema, men dessa ändringar kommer att försvinna om du ändrar eller updaterar your theme. Det är därför det är bättre om du skapar ett barntema och sedan gör dina ändringar i barntemat.
In your page template file, you need to add this line of code where you want to display child pages.
<?php wpb_list_child_pages(); ?>
Det är all. Ditt theme kommer nu automatiskt att upptäcka barntema pages och visa dem i en vanlig lista.
Du kan customize formaten med CSS och format. Här är ett exempel på hur OptinMonster website visar parent page och sub pages:
Vi hoppas att den här artikeln hjälpte dig att lista child pages för en parent page i WordPress. Du kanske också vill se vår guide om de viktigaste sidorna att skapa på en new WordPress-webbplats, och vår jämförelse av de bästa drag and drop WordPress page builders för att skapa customizes layouts utan någon kod.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
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!
Philip says
Hello this works, except that the parent is also displaying, how do i show just the child pages, thanks
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.
Administratör
Sachit Shori says
Thank you so much. You saved me.
WPBeginner Support says
You’re welcome
Administratör
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
WPBeginner Support says
You would change the two instances of menu_order in our code to be: post_title
Administratör
Iyke O. says
How do I make the list collapsible on sidebar.
WPBeginner Support says
To make it collapsable you could use an accordion plugin such as one of the ones from our article here: https://www.wpbeginner.com/showcase/best-wordpress-accordion-plugins/
Administratör
Stacie says
Easy to follow and did the job. Thanks so much for sharing!
WPBeginner Support says
You’re welcome, glad our content could be helpful
Administratör
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?
WPBeginner Support says
You could add your CSS class in the ul section of the function
Administratör
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
WPBeginner Support says
Glad our tutorial could help
Administratör
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.
Administratör
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.
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?
vicky says
how to get child page ids not the granchild ids…………….pls help im a bigginner
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.
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.
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?
WPBeginner Support says
Hi Boris,
Please try adding this code to your theme’s functions.php file or a site-specific plugin.
1-click Use in WordPress
Administratör
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 !!
WPBeginner Support says
Hi Frederic,
Glad you found it useful
You may also want to subscribe to our YouTube Channel for more WordPress video tutorials.
Administratör
Mariano says
Hi!
Thanks for the code. How can I display the featured image of each child page?
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?
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?
Razvan says
What if I want to display child posts, not child pages?
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?
Michael Feske says
Great, but it works not
add_shortcode is correct or must it be add_filter https://www.wpbeginner.com/wp-tutorials/how-to-use-shortcodes-in-your-wordpress-sidebar-widgets/ ?
with add_shortcode is error Fatal error: Uncaught Error: Call to undefined function add_shortcode()
with add_filter is no error but it works nort
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
Jeffrey Fry says
How can you also display the date of the child page?
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.
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);
Jean Bishop says
I am using this code and it works great. Is it possible to also display categories in menus along with pages?
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
Zakhar says
How can i create shortcode with param, for example, [wpb_childpages id=”1″], where id=”1″ is an id of parent page?
Strand says
Hi,
Is it possible to limit the links to a specific number such as maximum 12 child pages?
Thanks
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.
Quantum-mecha says
How do I add pagination for Child Page?
Thanks!
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!
Mehar says
Really useful. Thank you.
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
Andrew Roberts says
For the non-shortcode option, you might want to let users know they need to either change
return $string;
toecho $string;
orin their page template echo out the function
echo page_list_child_pages();
Thanks to Erik for pointing this out above
Meredith Adams says
Thank you!
Gaby says
Thank you! I was wondering why the code wouldn’t work…
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.
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.
Michael says
how can i customized this to just display the child page of a specific page?
Yester says
How do u add a active class on the current ?
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
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');
Daniela says
This is great! Is there a way to do the same for Custom Post Types that have child posts?
Caroline says
Also wondering!
If anyone knows, please help!
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!
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.
Razvan Zamfir says
Hello!
Nice snippet, but how do I list only grandchild pages?
Thank you!
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 . ”;
}
WPBeginner Staff says
In order to execute a shortcode in WordPress templates you need to add it like this:
Matt Rock says
I couldn’t get the template code ”wpb_list_child_pages();” to work, but echo shortcode did the trick. Cheers!
Erik says
Just change the ”return $string” to ”echo $string” (this will print out the pages).
fariha says
thanks, it worked
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?
Elena Rapisardi says
Great explanation!!
Is there a way to display always the parent pages?
Quin says
This is brilliant, thanks.
Is there a way to adapt it so the Parent displays the Grandchild, and not the Child?