In this tutorial to show How to get child pages of specific parent page in sidebar dynamically
Ex : Products is a parent page and Product-1,product-2,etc are child page(sub-pages)
STEP 1 : To get child pages
Add the below code in functions.php
function show_all_children($parent_id, $post_id, $current_level)
{
$top_parents = array();
$top_parents = get_post_ancestors($post_id);
$top_parents[] = $post_id;
$children = get_posts(
array(
'post_type' => 'page'
, 'posts_per_page' => -1
, 'post_parent' => $parent_id
, 'order_by' => 'title'
, 'order' => 'ASC'
));
if (empty($children)) return;
echo '<ul class=" sub-pages children level-'.$current_level.'-children">';
foreach ($children as $child)
{
if(is_page($child->ID ))
{
$sctive="child-page-active"; //class of current(active) child page
echo '<li class="p-4 mt-0 '.$sctive.'"';
}
else
{
echo '<li class="p-4 mt-0" ';
}
echo '>';
echo '<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>
<a class="" href="'.get_permalink($child->ID).'">';
echo apply_filters('the_title', $child->post_title);
echo '</a>';
// now call the same function for child of this child
if ($child->ID && (in_array($child->ID, $top_parents)))
{
show_all_children($child->ID, $post_id, $current_level+1);
}
echo '</li>';
}
echo '</ul>';
}
STEP 2 : To display the list of child pages
Note : In this i’ve displayed the child pages title as list ,you can add div, section,etc instead of ‘<li>’ tag.
Add this code to where ever you want to display the lists.Add in sidebar ‘text widget’ to get the list in sidebar.
<h2>
<?php
$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);
}
?>
</h2>
<?php
$parents_ids = get_post_ancestors($post->ID);
$top_parent_id = (count($parents_ids) > 0) ? $parents_ids[count($parents_ids)-1] : $post->ID;
show_all_children($top_parent_id, $post->ID, 1);
?>
Add the above code and check it . you can get the list of child pages titles in the sidebar.







Leave a Reply