PHP DevelopmentWordpress Development

Display List of child pages in page template

In wordpress, there is function called wp_list_pages(); which accepts one argument that is an associative array and returns
Pages and child pages in wordpress

In WordPress, displaying a list of child pages within a parent page enhances navigation and user experience. This feature organizes hierarchical content efficiently, allowing visitors to easily explore related topics. By utilizing built-in functions or plugins, dynamic lists of child pages can be automatically generated and presented on parent pages.

In WordPress, you can get the ID of parent page and display go back & put parent page’s link. Read the post here

Get list of child page in WordPress and display in page

In WordPress, there is function called wp_list_pages(); which accepts one argument that is an associative array and returns pages as a list. In the associative array you have the option to select what to display.

An associative array: in PHP is a collection of key-value pairs where keys are user-defined and used to access corresponding values. Unlike indexed arrays, where keys are numeric and automatically assigned, associative arrays allow keys to be specified by the programmer. This enables the storage and retrieval of data using meaningful key-value pairs, providing flexibility and convenience in organizing and manipulating data in PHP scripts. Example of associative array:

$flagSpecs => array(
'Color' => 'Red',
'Size' => '2m',
'Textile' => 'Khakki'
);

To display child pages of a page inside the page template you could use wp_list_pages(array('child_of' = get_the_ID())); but this line of code only displays child pages in only parent pages but will not display in child pages. This is important if you have more than one child pages and want to add other child pages list for easy navigation. So, to do so, you have to check if the current page is parent or child page. If the page is parent you could get 'child_of' => get_the_ID() directly but if the page is child page, you have to get the 'child_of' => the Parent Page

<?php
$parentPage = wp_get_post_parent_id(get_the_ID());
if ($parentPage) {
$childPagesOf = $parentPage;
} else {
$childPagesOf = get_the_ID();
}

wp_list_pages(array(
'title_li' => NULL,
'child_of' => $childPagesOf
));

The if statement used above checks if the page has parent page & if the page has parent, it assigns ID of parent page to the variable $parentPage but if the page is main page, it assigns the page ID to the variable $parentPage.

—- Thankyou for Reading —-

Shares:

Related Posts

Top Categories

PHP Development
22
WordPress Theme Development
21
Wordpress Development
18
WordPress JS Development
13
Show Comments (0)
Leave a Reply

Your email address will not be published. Required fields are marked *